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

What is the mechanism by which nodes handle multiple requests simultaneously?

Lately, I've delved into the world of NodeJs, trying to grasp how it handles multiple concurrent requests. It's fascinating that NodeJs operates on a single-threaded event loop architecture, where only one statement executes at a time on the main ...

Issue with displaying content within a custom element for children was not seen

The content within the 'Child content' span is appearing in the Light DOM, but for some reason it's not being displayed on the actual page (refer to the screenshot provided). Does anyone have any insights as to why it might not be visible? ...

tips for creating a mobile-friendly responsive button

I have been scouring the internet for a solution to this issue. Essentially, I am trying to position the button on the right side in desktop view. Here is an example: chrome view However, when the site is resized or viewed on mobile devices, the button sh ...

XSLT - Dividing table into three columns while maintaining continuity on the same page

I'm looking for a solution where I can display a long two column table in a three-column page layout. The table should seamlessly flow from one column to the next, maintaining its headers throughout. Current attempts show the entire table in just one ...

Create an image on a node's backdrop using a library of graph theory/networking techniques

I have a set of data that I need to visually represent as a graph on a web browser. While creating the graph itself is not an issue, I am looking to dynamically draw unique icons for each node. These icons are specific to the characteristics of each node ...

Tips for Improving the Naming Conventions of CSS Modules

I currently have the following setup in my webpack.config.js: { test: /\.css$/, use: [ {loader: "style-loader"}, { loader: "css-loader", options: { modules: true, importLoaders: 1, s ...

Where should the defer.resolve be placed when executing a function asynchronously in a loop using JavaScript?

As someone coming from a java/python background, I am venturing into the world of JavaScript. My current task involves creating a product list with detailed descriptions of its children included in a JSON array. Here is an example of what I want to achiev ...

Experiencing unexpected output from Angular model class method

I have developed a user-friendly Invoicing & Inventory management application that showcases a list of invoices for each customer. However, there seems to be an issue with the calculation of the Grand Total function, which I am struggling to rectify due to ...

Higher Order Component for JSX element - displaying JSX with wrapped component

I am looking to utilize a ReactJS HOC in order to implement a tooltip around JSX content. The function call should look similar to this: withTooltip(JSX, "very nice") To achieve this, I have created the following function: import React from "re ...

Optimize Your Reactstrap Carousel Images for Responsiveness

Despite my extensive search efforts, I have found very limited documentation on how to make images within a ReactStrap carousel responsive to resizing. While the ReactStrap carousel itself is responsive, the images inside it do not resize accordingly. So ...

What is the best way to contain my content within a bordered box?

As a beginner in HTML and CSS, I have successfully created a basic website with a simple menu at the top that includes links to different pages like "Home," "About," and "Contact." The website will mainly feature information and images, but I believe it wo ...

Ways to initiate state transition from child component to parent component using React Hooks?

In the parent component, I have the following: const [updateQuantity, quantity] = useState(1); const handleChangeQuantity = e => { console.log(e.target.value); console.log("TEST"); updateQuantity(e.target.value); }; I the ...

When attempting to declare a functional component in React utilizing styled-components in TypeScript, an error is encountered stating "No overload matches this call."

Playground https://codesandbox.io/s/typescript-type-checking-question-0b42t Sample Code type BadgeTypes = { success: string; secondary: string; alert: string; text: string; }; type Theme = { fonts?: object; borderRadius: string; primary?: o ...

Is Dealing with Multiple AJAX Requests a Pain?

Currently, I am utilizing AJAX to retrieve a list of active streams from TwitchTV along with their viewers, updating every second. Sometimes the stream list can become quite long, so my plan is to divide the AJAX requests into 2 or 3 parts: 1) Obtain Numb ...

Is your CSS not reflecting changes in Node.js?

I am having trouble getting the CSS to update in the browser using Browser Sync via Gulp on Node.js. What could be the issue? Below is my Gulp.js file: var themename = 'playtest haha 1'; var gulp = require('gulp'), // Prepare ...

Step by step guide on how to connect a stylesheet in CSS

Hey there, I recently attempted to link a style sheet in my HTML for the first time. Unfortunately, I encountered an issue where it didn't work. Here's the code I used: <link href="css/StyleSheet.css" rel="stylesheet" type="text/css" /> W ...

Navigate to the parent element in the DOM

Looking to add some unique styling to just one of the many Mat dialog components in my project. It seems like modifying the parent element based on the child is trickier than expected, with attempts to access the DOM through the <mat-dialog-container> ...

Replicate the form to a new one while concealing the elements and then submit it

Initially, I was working with just one form. Now, I find myself in a situation where I need to utilize a different form which contains the same inputs. This is necessary because depending on the action taken upon submission, different processes will be tri ...

Angular JS is having some issues with rendering the style correctly

How can I make input fields turn pink before values are entered and green after values are entered? Currently, the styling only applies to the first row. What could be causing this issue? <script src="https://ajax.googleapis.com/ajax/libs/angularjs ...

Load image in browser for future display in case of server disconnection

Incorporating AngularJS with HTML5 Server-Side Events (SSE) has allowed me to continuously update the data displayed on a webpage. One challenge I've encountered is managing the icon that represents the connection state to the server. My approach inv ...