This is a PHP project, and I’m trying to use JavaScript to toggle my navigation bar in mobile view. By clicking on the navigation bar(hamburger), it will drop down or close the menu using an event listener that toggles the menu’s class. However the function is not been executed on this page.
I want to provide a background on how my backend works: There is a file (articles.php) that dynamically renders a list of articles from a MySQL database. The logic that interacts with the database is in articles_model.inc.php, and the logic that displays the data is in articles_view.inc.php..
Retrieval of the data from the database(articles_model.inc.php):
function get_articles(object $pdo){
$query = "SELECT article_title, article_content, created_at, id FROM articles;";
$stmt = $pdo->prepare($query);
$stmt->execute();
$articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $articles;
};
Logic to display this articles(articles_view.inc.php):
function show_articles($articles){
if (!empty($articles)) {
echo "<div class='articles-div'>";
foreach ($articles as $article) {
$id = $article["id"];
list($datePart, $timePart) = explode(' ', $article['created_at']);
$date = DateTime::createFromFormat('Y-m-d', $datePart);
$formattedDate = $date->format('F j, Y');
echo "<div class='article-card'>";
echo "<strong class='article-title'>{$article['article_title']}</strong>";
echo "<h6 class='date-created'>Posted on $formattedDate $timePart</h6>";
echo "<a href='../article/article.php?id=$id' class='article-content'>{$article['article_content']}</a>";
echo "</div>";
}
echo "</div>";
} else {
echo "<p class='welcome-text'>You are not logged in and cannot create articles</p>";
}
};
Inside articles.php:
The articles will be displayed using the show_article function from articles_view.inc.php
<?php
show_articles($articles);
?>
In articles_view.inc.php, the dynamically rendered UI includes a link that passes an ID to article.php. This page uses the ID to make a database request, and it is the page where JavaScript isn’t functioning.
Now that I’ve provided background knowledge of how my site works, I will explain what I have tried:
In an article.js file, I used a DOM event listener to obtain the id attributes of the toggler and menu HTML elements. I then utilized these id attributes to execute a function that changes the class of the HTML element.
document.addEventListener('DOMContentLoaded', function() {
const toggler = document.getElementById('navbar-toggler');
const menu = document.getElementById('navbar-menu');
toggler.addEventListener('click', function() {
menu.classList.toggle('active');
});
});
But since javascript won’t work on this page(article.inc.php) , nothing happens. The function is not even being executed.
NOTE: articles.php and article.php are differnt files.
social_freak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1