Unbinding or undoing an 'onclick' event when another 'onclick' event is triggered

I am facing an issue where clicking on elements with 'onclick' functions works as expected, but when I click on a different element with another 'onclick' function, the first one remains active. What I actually want is for the previous function to be reversed or disabled when a new function is called.

These h1 tags are acting as navigation items, and upon clicking them, their styles change accordingly.

Below is the code snippet:

function aboutActive() {
    var about = document.querySelector('.about');

    about.classList.toggle('about-active');
}

function contactActive() {
    var contact = document.querySelector('.contact');

    contact.classList.toggle('contact-active');
}

function discoverActive() {
    var discover = document.querySelector('.discover');

    discover.classList.toggle('discover-active');
}

function signUpActive() {
    var signUp = document.querySelector('.sign-up');

    signUp.classList.toggle('signUp-active');
}
 .about {
     position: absolute;
     left: 70.8%;
     top: 5%;
     transition: transform 0.8s ease-in;
     transition: 0.8s ease-in;
}
 .contact {
     position: absolute;
     left: 56%;
     top: 24%;
     transition: transform 0.8s ease-in;
     transition: 0.8s ease-in;
}
 .discover {
     position: absolute;
     left: 52.7%;
     top: 43%;
     transition: transform 0.8s ease-in;
     transition: 0.8s ease-in;
}
 .sign-up {
     width: 100%;
     position: absolute;
     left: 62.6%;
     top: 63%;
     transition: transform 0.8s ease-in;
     transition: 0.8s ease-in;
}
/* Styles changed by JS */
 .about-active {
     transform: translateX(-30%);
     color: #ffffff;
}
 .contact-active {
     transform: translateX(-22%);
     color: #ffffff;
}
 .discover-active {
     transform: translateX(-24%);
     color: #ffffff;
}
 .signUp-active {
     transform: translateX(-14.2%);
     color: #ffffff;
}
<h1 class="about" onmouseover=cursorEnlargeLarge() onmouseout=cursorNormal() onclick="aboutActive()">ABOUT</h1>
<h1 class="contact" onmouseover=cursorEnlargeLarge() onmouseout=cursorNormal() onclick="contactActive()">CONTACT</h1>
<h1 class="discover" onmouseover=cursorEnlargeLarge() onmouseout=cursorNormal() onclick="discoverActive()">DISCOVER</h1>
<h1 class="sign-up" onmouseover=cursorEnlargeLarge() onmouseout=cursorNormal() onclick="signUpActive()">SIGN UP</h1>

These functions toggle through the styles when clicked on. My concern is that the previously activated function does not deactivate automatically when a new function is triggered. How can I modify it so that any previous functions get reversed or reset?

Answer №1

function removeClasses(ele){
    let cl = ele.classList;
    ele.classList.remove(cl[cl.length - 1], cl[cl.length - 2]);
}

function activateAbout() {
    let about = document.querySelector('.about');
    let current = document.querySelector(".current");
    if(current) removeClasses(current);
    about.classList.toggle('about-active');
    about.classList.add("current");
}

function activateContact() {
    let contact = document.querySelector('.contact');
    let current = document.querySelector(".current");
    if(current) removeClasses(current);
    contact.classList.toggle('contact-active');
    contact.classList.add("current");
}

This code adds the 'current' class to an active element.

If the 'current' class already exists, it removes the last two classes of the element with the 'current' class.

It may not be perfect, but it gets the job done.

(This is my first answer on Stack Overflow, so please go easy on me)

Answer №2

As per my understanding, your requirement is to deactivate the function previously clicked when you click on another function.

 var home = document.querySelector('.home');
 var services = document.querySelector('.services');

function homeActive() {
    home.classList.toggle('home-active', true);
}

function servicesActive() {
   
home.classList.toggle('home-active', false);
services.classList.toggle('services-active');

}

Answer №3

Incorporate a Reset feature prior to clicking on any H1 element, which will reset all previously clicked h1 tags.

function aboutActive() {
  resetAll();
  var about = document.querySelector('.about');

  about.classList.toggle('about-active');
}

function contactActive() {
  resetAll();
  var contact = document.querySelector('.contact');

  contact.classList.toggle('contact-active');
}

function discoverActive() {
  resetAll();
  var discover = document.querySelector('.discover');

  discover.classList.toggle('discover-active');
}

function signUpActive() {
  resetAll();
  var signUp = document.querySelector('.sign-up');

  signUp.classList.toggle('signUp-active');
}

function resetAll() {
  var getheading = document.getElementsByTagName("H1");
  [].forEach.call(getheading, function(el) {
    var classes = el.className.split(" ").filter(c => !c.endsWith("-active"));
    el.className = classes.join(" ").trim();

  })
}
.about-active {
  transform: translateX(-30%);
  color: #ffffff;
}

.contact-active {
  transform: translateX(-22%);
  color: #ffffff;
}

.discover-active {
  transform: translateX(-24%);
  color: #ffffff;
}

.signUp-active {
  transform: translateX(-14.2%);
  color: #ffffff;
}
<h1 class="about" onclick="aboutActive()">ABOUT</h1>
<h1 class="contact" onclick="contactActive()">CONTACT</h1>
<h1 class="discover" onclick="discoverActive()">DISCOVER</h1>
<h1 class="sign-up" onclick="signUpActive()">SIGN UP</h1>

Answer №4

So my solution was to simply eliminate the active class when I execute the function:

function aboutActive() {
var about = document.querySelector('.about');
var contact = document.querySelector('.contact');
var discover = document.querySelector('.discover');
var signUp = document.querySelector('.sign-up');

about.classList.toggle('about-active');
contact.classList.remove('contact-active');
discover.classList.remove('discover-active');
signUp.classList.remove('signUp-active');

}

I have to repeat this process for every h1 element which may not be the most efficient way, but it gets the job done.

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

Change the CSS property to override the text-overflow with ellipsis

In my specific scenario, I need to override the default ellipsis behavior that adds '...' to text when using 'text-overflow: ellipsis', and instead use two stars **. Is there a way to achieve this using only Pure CSS? It is important t ...

Determine the aspect ratio of the image and incorporate it into the query string

In my current code, I am extracting the dimensions of an image obtained from a cropper tool. I then calculate the aspect ratio of the image by dividing the height by the width. This value is then incorporated into the query string url: urlLocation + imag ...

"Browser compatibility issues: 404 error on post request in Firefox, while request is

When following this tutorial on React and PostgreSQL, the app should display the JSON fetch in the bash terminal around the 37-minute mark. However, there seems to be a problem as there is no feedback showing up on the npm or nodemon servers. After tryin ...

"Extracting information from a database in Angular Laravel to create a Chart.js display - a step-by-step

Currently, I am working on developing a dashboard application that includes various charts. My aim is to customize the data displayed in each user's chart based on information retrieved from a database. This is how my setup looks like: HTML <div ...

What is the best way to include React globally when running unit tests?

In my Rails project, I have integrated the react-rails gem, which sets up a global variable like this: window.React = React; While this is convenient for regular usage, it causes issues when running unit tests with Jest because the global React variable ...

Running a JavaScript animation within an Electron environment

My curiosity lies in developing man-machine interfaces using Electron. Currently, I am experimenting with a Star Trek life signs monitor demo. I came across this code that can be easily customized to create vertical and horizontal movements: http://jsfiddl ...

Discover an Effective Approach for Transmitting Form-Data as a JSON Object

Hey there! I'm encountering a bit of an issue with sending some data as a JSON object. The problem arises when trying to send images using FormData. It seems like I need to convert my form data into a single JSON object. Can anyone assist me with this ...

Troubleshooting problem with jQuery UI accordion and sortable feature

I've run into an issue with the sortable functionality of accordion. I am attempting to drag and reorder the <h3> elements, but for some reason, the sorting is not functioning as expected. I followed the instructions from the official demo (here ...

A guide on embedding text onto the bottom of an image in Material-UI GridList using Reactjs

I'm currently developing a Mern-stack application and using Material-UI for the frontend. My GridList is functioning correctly, but I want to position my description text at the bottom of the image rather than in front of it. However, when I try to a ...

Eliminating the border of a table that is contained within a cell

I am facing an issue with a nested table where I need to remove the borders from specific cells (around A and B). Here is the code snippet: <style> .withBorders tr td{ border: 1px solid black !important ; } .withBorders table. ...

Tips for extracting information from a website with Selenium using Python

I am currently working on a project that requires me to extract certain information using Selenium from a webpage. The elements I need are not directly visible in the page's code, indicating they may be generated by JavaScript. Here is a snippet of my ...

Error in Node.js: the function "myFunction" is not defined

Utilizing the fcm-node package to facilitate sending notifications from the Express API route to the app via a registration token. The function being used is as follows: const FCM = require('fcm-node'); const serverKey = ... const fcm = new FCM( ...

What is the most efficient way to iterate through an array to push properties into an object nested within another array?

I have been working on a small Angular application that functions as a scheduler, allowing users to input a Name, Start and End dates, and toggle a boolean checkbox through a form. One challenge I am facing is trying to assign the names entered by each use ...

Implementing Ajax calls to dynamically update Datatable results

Currently integrating Datatables.js with an ajax call for data retrieval. The json response I'm receiving is as follows: "success":true,"message":"","items":[{"id":"1","ip_address":"127.0.0.1","email... My data is stored within the data.items array ...

Guide on submitting a reply to Harvard's "Guess my Word" challenge using JSoup

I am currently working on developing a bot to enhance my gameplay in Harvard's intriguing "Guess my Word!" game. After some exploration, I found out about a post request feature available through Chrome's "inspect element" functionality when a pl ...

Is it necessary to use a specific button to submit on Return (Enter)?

In a wizard-type form, there are two buttons present. The Back button is positioned on the left side, while the Next button is located on the right side. For an example of this setup, visit http://jsfiddle.net/WSwb7/1/. Please note that submitting the form ...

After clicking the submit button, how can I eliminate the following: "config.php?username=++psw&Text=psw&submit=send?" and remain on the same page?

Whenever I hit the submit button on my form, PHP completes its task but instead of staying on the page (or simply reloading it), I am redirected to the same URL with '/config.php?username=technologies.%0D%0A++&submit = Send ". Is there a way ...

I am encountering an issue where I am sending an AJAX request to a PHP file with the datatype set as JSONP, but I

When I click on the submit button, I am sending a variable to sendmail.php. However, PHP is showing that 'contactname' is undefined. Why is this happening? Here is the code snippet: var name = document.getElementById('stream_cotactname&apo ...

Visualizing live data streaming from MySQL

I am currently using this code to retrieve values from a database and create a basic line graph (showing response time to an alert vs. UTC time). Everything works smoothly when the data is static, but now I want to try retrieving the data in "real-time" (j ...

Combining properties from one array with another in typescript: A step-by-step guide

My goal is to iterate through an array and add specific properties to another array. Here is the initial array: const data = [ { "id":"001", "name":"John Doe", "city":"New York&quo ...