The event handler is not being triggered when selecting the tag

Currently working on a project where I am utilizing vanilla HTML/CSS/JS. My goal is to hide all items on a page initially, set a default option in a select tag, display only the element with the selected ID, and allow the user to choose different time periods using a dropdown menu to display the corresponding element.

However, I am encountering an issue with my code structure. I have set up the function as follows, including a console log to track its execution. Despite this, the log only appears once and the event handler seems to not be firing correctly, no matter which option I select from the filter. I believe I have followed the examples closely, so I'm unsure of what the problem might be. Can you identify the issue?

var day = document.getElementById("day");
var week = document.getElementById("week");
var month = document.getElementById("month");

period = document.getElementById("filter");
function loadPost(period) {
    // Hide all posts
    day.style.display = "none";
    week.style.display = "none";
    month.style.display = "none";
    switch (period) {
        case day:
            showDay();
            break;
        case week:
            showWeek();
            break;
        case month:
            showMonth();
            break;
    } 
    console.log(period);
}
function showDay() {
    day.style.display = "block";
}
function showWeek() {
    week.style.display = "block";
}
function showMonth() {
    month.style.display = "block";
}
period.addEventListener("change", loadPost(period.value));
        <div class="most-popular">
            <h1>Most Popular</h1>
            <label for="most-popular-filter">Filter:</label>
            <select name="most-popular-filter" id="filter">
                <option value="day">Day</option>
                <option value="week">Week</option>
                <option value="month">Month</option>
            </select>
            <div class="content-box" id="day">
                <img src="images/placeholder.png" alt="most-popular">
                <h2>Most Popular 1</h2>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quae.</p>
            </div>
            <div class="content-box" id="week">
                <img src="images/placeholder.png" alt="most-popular">
                <h2>Most Popular 2</h2>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quae.</p>
            </div>
            <div class="content-box" id="month">
                <img src="images/placeholder.png" alt="most-popular">
                <h2>Most Popular 3</h2>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quae.</p>
            </div>      
        </div>

Answer №1

Implement a callback function that triggers another function:

eventListener.addEventListener("click", ()=>callFunction());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Uniqid in React fails to generate unique IDs

Currently working on creating my first react project and developing a todo list. I have incorporated the uniqid generator into my todo object, but it seems to be returning an empty id rather than a random one. Oddly enough, if I move the todo state outsi ...

Update the less mixin

I attempted to eliminate the border radius from all Bootstrap elements by creating a custom-mixins.less file with the following lines in it. My intention was for these lines to overwrite the original .border-radius mixin, but unfortunately, it did not work ...

Assign AngularJS directives to DOM element using controller

I'm experimenting with the idea of controlling the angular directive('ng-show') from the controller. Here is what I'm attempting to do: var node = `<div ng-show="this.length > 5">...</div>`; var child = document.creat ...

Capturing the process exit event in Express: A guide

process.on('exit', async () => { console.log('updating') await campaignHelper.setIsStartedAsFalse() console.log('exit') process.exit(1) }) This code snippet is designed to trigger an update in the database before t ...

Creating Production Files for Web using RxJs and TypeScript

I am interested in developing a JavaScript Library using RxJs (5.0.0-Beta.6) and TypeScript (1.8.10). My TypeScript file is successfully compiling. Below are the files I have: MyLib.ts: /// <reference path="../../typings/globals/es6-shim/index.d.ts" ...

Analyzing Data for Distributed / External Pages

Our team is currently exploring options for tracking metrics on content we produce for external pages. We are considering various approaches such as creating our own JavaScript, using a tracking pixel, or adapting Google Analytics to fit our needs. We wou ...

Encountering issues with creating a session in Selenium/webdriver while utilizing Safari 12

Ever since making the update to Safari 12, my automated scripts have been encountering a new error: SessionNotCreatedError: Request body does not contain required parameter 'capabilities'. (Interestingly, this error is exclusive to Safari and d ...

Having difficulty retrieving data when running a React JS app on the IP address 192.168.XX.XXX

I'm attempting to retrieve backend data in a React app using the Fetch API. It's functioning correctly when I run the React app on localhost, but if I change the address from localhost to an IP, it stops working and displays Unhandled Rejection ( ...

Changing the hue of individual pixels on an HTML canvas to a different color while maintaining their original shading

I have created a function that enables me to draw an image on a hidden canvas temporarily in order to modify colors and change everything except solid black to a specific color while preserving the original white "shade". However, when attempting to execu ...

Ways to troubleshoot and resolve the jQuery error with the message "TypeError: 'click' called"

I am currently developing a project for managing Minecraft servers, focusing on a configuration panel. I have set up a form that users need to fill out in order to configure the settings and send the values using Ajax. However, I encountered an error: Type ...

Issue with variable passing during image upload

I am attempting to include an upload button alongside each recipe on my website. In order to save the image path next to each recipe in my database, I need to pass the recipe ID value during the image upload process. However, I keep encountering the same e ...

What is the best way to retrieve ViewBag data using jQuery?

Greetings, I am currently in the process of developing a web application using MVC5. Within this application, I have implemented a login form that consists of fields for both username and password: @using (Html.BeginForm("ClickAction", "Login", FormMethod ...

Steps for updating a text section beneath a carousel

I'm looking to enhance my webpage with a bootstrap carousel, which is pretty standard. However, I want the content under each slide to change dynamically, but I'm struggling to make it work. As a newbie, I could use some guidance. I've atte ...

What's the reason "console.log()" doesn't function on this particular site?

When I go to https://www.google.com/ and enter console.log("Hello world!") into the Chrome DevTools console, it prints "Hello world!" as expected. However, when I try the same command on , nothing shows up in the console. Why doesn't it work for this ...

Unable to switch the text option

[Fiddle] I'm currently working on a project where I want pairs of buttons to toggle text by matching data attributes. While I can successfully change the text from "Add" to "Remove" on click, I am facing an issue with toggling it back to "Add" on the ...

Upon clicking a button, initiate an Ajax call to retrieve a value from the code behind (aspx.cs) and display it in an input field on the same page

I am a beginner in the world of AJAX and encountering a problem. I need to initiate an AJAX call when a button is clicked. The goal is to send the value of an input field to the code behind page, aspx.cs, and then display the response from that same input ...

A surprise awaits in IE with the unusual appearance of a div display

body { background: #9cdcf9 url(/images/left_cloud.png) bottom left no-repeat; font-family:\"Trebuchet MS\"; padding:0; margin:0; border:0; } #cloud-container { width: 100%; background: url(/images/right_cloud.png) bott ...

Animation displayed on page load before running

Is there a way to ensure that my animation runs smoothly without any lag or jankiness, either while the page is loading or immediately after loading? I have attempted to preload the images using a preload tag in the header of my HTML, but unfortunately, t ...

The ng-repeat-start feature is not functioning properly across different levels

I am attempting to utilize the ng-repeat-start directive in order to construct a table that resembles the following: https://i.sstatic.net/Qgc91.png The structure of my JSON data is as follows: [ { "name": "Chapter 1", "parts": [ { ...

Deciphering click event parameters in an AngularJS application

Currently, I am in the process of improving a feature in an existing application that has already been deployed. Unfortunately, all the JavaScript code is minified, and I only have access to the HTML files. I need to implement a function that triggers when ...