The first instance of an object retains its class, but subsequent instances may change

Trying to articulate my query concisely is proving challenging. Let me do my best to provide a clear explanation.

The fixed header on my website features 4 buttons. I've created a JavaScript file that alters the class of each button when clicked. The class changes to "menuButtonSelected" for the clicked button and switches all others to "menuButton". Below is the JavaScript code:

function setButtonOne() {
    // Function logic for button one
}

function setButtonTwo() {
    // Function logic for button two
}

function setButtonThree() {
    // Function logic for button three
}

function setButtonFour() {
    // Function logic for button four
}

Each button has a unique ID (buttonOne, buttonTwo, buttonThree, buttonFour). In my HTML file, I assign the onclick attribute based on the button's ID. For example, buttonOne would have an onclick value of setButtonOne().

Here's a snippet of the relevant HTML code:


            <a href="#home"><div id="buttonOne" class="menuButtonSelected" onclick="setButtonOne();titleHome();">
                <p class="menuText">Home</p>
            </div></a>

            <a href="#projects"><div id="buttonTwo" class="menuButton" onclick="setButtonTwo();titleProjects();">
                <p class="menuText">Projects</p>
            </div></a>

            <div id="buttonThree" class="menuButton" onclick="setButtonThree();">

            </div>

            <div id="buttonFour" class="menuButton" onclick="setButtonFour();">

            </div>

The issue lies here.

Upon revisiting my site, I noticed that clicking the second button doesn't immediately trigger a change. Subsequent clicks work fine. Oddly, this problem occurs only with the second button while the third and fourth ones function correctly. It seems like the menuButtonSelected class reverts to the first button when clicking the second button.

I suspect there might be a flaw in the setButtonTwo() function, but I haven't identified it yet.

Any suggestions for resolving this?

Note: To view the website live, click here (content in Dutch).

Answer №1

To prevent the page from submitting, it is necessary to ensure that each JavaScript function returns false.

Below is the HTML code snippet:

<a href="http://www.ysbakker.eu/site/index.html#home"><div id="buttonOne" class="menuButtonSelected" onclick="return setButtonOne();">
    <p class="menuText">Home</p>
</div></a>

<a href="http://www.ysbakker.eu/site/index.html#projects"><div id="buttonTwo" class="menuButton" onclick="return setButtonTwo();titleProjects();">
    <p class="menuText">Projecten</p>
</div></a>

<div id="buttonThree" class="menuButton" onclick="setButtonThree();">

</div>

<div id="buttonFour" class="menuButton" onclick="setButtonFour();">

</div>

Here are the corresponding JavaScript functions:

function setButtonOne() {
    if(document.getElementById("buttonOne").className == "menuButton") {
        document.getElementById("buttonOne").className = "menuButtonSelected";
        document.getElementById("buttonTwo").className = "menuButton";
        document.getElementById("buttonThree").className = "menuButton";
        document.getElementById("buttonFour").className = "menuButton";
    }

    else if(document.getElementById("buttonOne").className == "menuButtonSelected") {
        // Do nothing
    }

    return false;
}

function setButtonTwo() {
    if(document.getElementById("buttonTwo").className == "menuButton") {
        document.getElementById("buttonTwo").className = "menuButtonSelected";
        document.getElementById("buttonOne").className = "menuButton";
        document.getElementById("buttonThree").className = "menuButton";
        document.getElementById("buttonFour").className = "menuButton";
    }

    else if(document.getElementById("buttonTwo").className == "menuButtonSelected") {
        // Do nothing
    }
    return false;
}

function setButtonThree() {
    if(document.getElementById("buttonThree").className == "menuButton") {
        document.getElementById("buttonThree").className = "menuButtonSelected";
        document.getElementById("buttonTwo").className = "menuButton";
        document.getElementById("buttonOne").className = "menuButton";
        document.getElementById("buttonFour").className = "menuButton";
    }

    else if(document.getElementById("buttonThree").className == "menuButtonSelected") {
        // Do nothing
    }
    return false;
}

function setButtonFour() {
    if(document.getElementById("buttonFour").className == "menuButton") {
        document.getElementById("buttonFour").className = "menuButtonSelected";
        document.getElementById("buttonTwo").className = "menuButton";
        document.getElementById("buttonThree").className = "menuButton";
        document.getElementById("buttonOne").className = "menuButton";
    }

    else if(document.getElementById("buttonFour").className == "menuButtonSelected") {
        // Do nothing
    }
    return false;
}

It's important to note that each JavaScript function must return false and that the onclick attribute in each button should return the value of the respective function.

For a working example, you can check out the JSfiddle link here.

Answer №2

I discovered a solution on my own: by redirecting to the complete URL path using my redirection page, I was able to resolve the issue. I changed the redirect from [domain]/site to [domain]/site/index.html, and now everything is working smoothly.

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

Saving changes made in HTML is not supported when a checkbox is selected and the page is navigated in a React application using Bootstrap

In my array, there are multiple "question" elements with a similar structure like this: <><div className="row"><div className="col-12 col-md-9 col-lg-10 col-xl-10 col-xxl-10"><span>Question 1</span></div ...

JWPlayer encounters an issue: "undefined" function is not defined

Can anyone lend a hand with this issue I'm facing? I'm attempting to upload a video using jwplayer but encountering errors. Here is the snippet of code I'm utilizing: <script type="text/javascript"> jwplayer("leg ...

What is the best method to display a component using a string in Vue 3?

I've been attempting to render a component from a string without success. Here are my codes: <template> <div v-html="beautifyNotification(notification)"></div> </template> <script> import { Link } from '@i ...

Is there a way to retrieve all documents based on the start and end of a specific day?

One common issue I am facing involves submitting a date to my nodejs server in a specific format

 2018-11-02T00:36:00+05:30 // The actual time should be 12:36AM However, when examining the document in my database (using studio 3T), the format appear ...

I am interested in setting up a flickr gallery where clicking on an image will display a pop-up showing the image along with its relevant tags, title, and photo ID

Page´s photo Hello there, I am currently working on creating a Flickr API using JavaScript and HTML. My goal is to search for photos and display them in an HTML page, but I'm struggling with implementing a pop-up feature that includes the photo' ...

I am having trouble getting the smooth scroll feature to work on my horizontally scrolling website

Hello, I've added jQuery smooth scrolling to my website but it doesn't seem to be working correctly. Instead of scrolling smoothly, the site now scrolls horizontally to the right. I have already tried using smooth-behaviour but that did not solve ...

A captivating opportunity for a web developer specializing in frontend design

Encountered an intriguing dilemma that has me stumped. There is a single stipulation: Only the json can be altered! I am struggling to meet this requirement: data.hasOwnProperty("\u{0030}") class JobHunter { get data() { return &ap ...

What is the best way to create a function that will return a Promise within an Express Route?

I am working with a business level database module named "db_location" that utilizes the node-fetch module to retrieve data from a remote server through REST API. **db_location.js** DB LOGIC const p_conf = require('../parse_config'); const db_ ...

Step-by-Step Guide: Exporting a div to a beautifully formatted PDF with NextJs

Currently, I am working on an app project that involves filling out forms and having the information automatically formatted into a div to generate CLP labels. My goal is to be able to export this div in pdf format while also being able to select sizes ran ...

The Bootstrap 4 column is not floating properly to the right as it is leaving a gap on the

My right sidebar is not floating to the right and has space from the right side. You can view it at this link: <div class="col-md-2 col-lg-2 col-sm-2" id="right-sidebar" style="background-color:orange; float: right; right: 0!important; width: 100%;"& ...

Tips for implementing Bootstrap pagination in VueJS 2

Here is how my website appears: Jobs.vue: <div id="jobs" class="job-item" v-for="(item, index) in showJobs" :key="index" > <router-link ...

Organizing angular shapes in alphabetical order

My drop down arrow has elements that are not properly sorted. I have been attempting to use the orderBy angular filter but have encountered some challenges. Upon further investigation, it seems the issue arises because the content I need displayed is neste ...

Is it necessary for me to use a .jsx extension when saving my React component files?

After working with React for a few months, I recently noticed that some of my files have the .js extension while others have the .jsx extension. Surprisingly, when I write JSX code in the .js files, everything still functions correctly. Is there any signif ...

An issue occurred while attempting to retrieve information from the database table

'// Encounter: Unable to retrieve data from the table. // My Code const sql = require('mssql/msnodesqlv8'); const poolPromise = new sql.ConnectionPool({ driver: 'msnodesqlv8', server: "test.database.windows.net", ...

Aligning text beneath a positioned span element

I have a code snippet where I am trying to center a number within a div and then center the units right below the number. The number is centered correctly, but the units are not aligning as desired. How can I achieve this layout? div.div1 { height: 20 ...

Reusable Code: How can you implement a function that calls itself multiple times in JavaScript?

My goal is to continuously update the current time every minute using a countdown timer. Unfortunately, my code seems to be malfunctioning as indicated by an error message in the Firebug console stating that the function getStatus() is not defined. How c ...

Using PHP associative arrays as null values in JavaScript functions

On my PHP webpage, I have 6 textboxes arranged like this: <html> <script type="text/javascript"> function add() { //Issue with PHP associative array not transferring to JS array var array = JSON.par ...

The issue of placeholder values not displaying correctly in a React project deployed on Vercel and Netlify

Currently utilizing the React hook-forms library to handle form values and input data validations. The Placeholder text is visible when testing on the development server (localhost), but it does not appear upon deployment, leading to confusion for users tr ...

When hovering over one div, both it and another div should be displayed simultaneously. The second div should continue to be displayed even when hovered over

I am looking to keep another div displayed when hovering over it - in this example, it says "hello." The div I want to remain visible is not a child element of the main div where I initiate the hover event. document.write("<base href=\"" + docum ...

Adding every single table located in a div onto the body of the document

In my code, there is a div containing 3 tables. var x = tempDiv.getElementsByClassName("hiscore_table"); I can confirm this because when I log it in the console, it shows like this: https://i.sstatic.net/iYBB8.png To organize the tables, I create a new ...