JavaScript: Use onclick events to change the class of a div on multiple divs

I have a jQuery script that allows for toggling of the parent class when #icon is clicked. Additionally, when the body is clicked, it reverts back to the original class. Now, I'm looking to achieve the same behavior when clicking on #item5 or #item4 as if it were #icon being clicked.

<div id="header_wrap">
    <div id="logo"></div>
    <div class="contact" id="ccontainer">
        <div id="form"></div>
        <div id="icon"><span id="getintouch">GET IN TOUCH</span></div>
    </div>

    <div id="menu_wrap">
        <ul id="menu">
            <li id="item1"><a  href="#">Home</a></li>
            <li id="item2"><a  href="#">About us</a></li>
            <li id="item3"><a  href="#">What we do</a></li>
            <li id="item4"><a  href="#">Portfolio</a></li>
            <li id="item5"><a  href="#">Contact us</a></li>
        </ul>
    </div>
</div>

While attempting to create my own jQuery solution to implement this feature, I've encountered some challenges due to my limited experience with JavaScript and jQuery. Here is the code snippet:

$('#icon').on('click', function(e){
    $(this).parent()
        .toggleClass('contact')
        .toggleClass('contactexpand');
});

$('body').on('click', function(e){
    $('#ccontainer')
        .removeClass('contactexpand')
        .addClass('contact');
});

$('#ccontainer').on('click', function(e){
    e.stopPropagation();
});

Answer №1

If you want to prevent the click event from triggering on all ancestor elements, remember to use event.stopPropagation within your click handler.


$(document).ready(function(){
    $('#icon, ul li').on('click', function(event){
        event.stopPropagation();
        $('#icon').parent()
            .toggleClass('contact')
            .toggleClass('contactexpand');               
    });
    
    $('body').on('click', function(e){
        $('#ccontainer')
            .removeClass('contactexpand')
            .addClass('contact');
    });
});

Answer №2

Make the following adjustments to the javascript code:

$('#icon, #ul > li').on('click', function(e){
    $("#ccontainer")
      or $(this).parent() *not entirely sure what you wanted to get*
    .toggleClass('contact')
    .toggleClass('contactexpand');
});



$('body:not(#icon, #ul > li)').on('click', function(e){
    $('#ccontainer')
    .removeClass('contactexpand')
    .addClass('contact');
});


$('#ccontainer').on('click', function(e){
    e.stopPropagation();
});

The #ul > li selector targets all elements with an id of #item(number)

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 best way to retrieve the @Url.Action url from a distinct script file?

Currently, I have organized my JavaScript file separately from my web pages. One issue I am encountering is that I am unable to write the following line of code: var url = '@Url.Action("AddTrade", "DataService")'; I hesitate to hard-code the UR ...

Which library do you typically employ for converting .mov files to mp4 format within a React application using Typescript?

As a web programming student, I have encountered a question during my project work. In our current project, users have the ability to upload images and videos. Interestingly, while videos can be uploaded successfully on Android devices, they seem to face ...

Ways to stop the default action in a confirm dialog while using Angular JS

Within my save function, I have the following: $scope.saveData = function () { if (confirm("Are you sure you want to save") === false) { return } // do saving When using the above code and clicking "yes," I encounter an error. Interestin ...

Table design with fixed left columns and header that adjust to different screen sizes

After reading various articles on this issue, I have been unable to find a solution. Most of the examples I've come across feature tables with a single row for the header and rows that consist of just one row, similar to a calendar. My table, on the o ...

Place the token within the Nuxt auth-module

Working on a project using the Nuxt auth-module. The Login API response is structured like this: data:{ data:{ user:{ bio: null, createdAt: "2021-06-29T12:28:42.442Z", email: "<a href="/cdn- ...

How to use Selenium in Python to target specific sub-elements

I am currently working with the following HTML code block: <tbody id="id_tbody"> <tr id="tr_project_0" class="project_tr clr01 hover" data-select-value="0" style="border-top: 1px dotted #B4B4B4;"> <td class="txtC"> <a href="/173537" ...

Having trouble with JQuery toggle()? Need some assistance with fixing it?

My attempts to utilize JQuery toggle functionality have been unsuccessful. The sliding up and down animation is not smooth and instead happens very quickly. I aim to achieve a sliding effect in my code similar to this example (Please refer to Website Des ...

Modifying the rows of an HTML table with jQuery: A step-by-step guide

I have an HTML table that I need to update its content. <div id='adf'> <table id='tbl1' runat='server' > <tr><td></td></tr> </table> </div> To update the table&apo ...

What could be causing useEffect to trigger only after the component has been mounted in NextJS?

I'm currently encountering an issue with my implementation of a useEffect function that is supposed to act like a componentWillMount, but the behavior is not as expected. Within the code for Component (as demonstrated in the Codesandbox provided belo ...

Using jQuery to communicate with a WCF service via Ajax results in receiving a bad

I'm struggling to set up an auto-complete feature, where I can successfully retrieve JSON data using Fiddler. However, when I try to implement it in my code, I keep encountering a connection error. Here is the code snippet: <htm> <Head> & ...

JSONP - dealing with unsuccessful AJAX request callbacks

My current task involves transferring data from one domain to another using jsonp. The data transfer process on the second server seems to be functioning well. However, I am facing an issue with the callback function. Despite successfully receiving the dat ...

Converting a PHP AJAX response JSON object into a jQuery array

In my development project, I have an en.php file containing an array as shown below: $lang = array( // MENU ITEMS "welcome" => "Welcome", "admin_panel" => "Administration panel", ... ); I want to store this array in a JavaScript arr ...

The setting of the custom user agent in the Chrome Extension Manifest Version 3 is not functioning correctly

We currently have an extension that consists of only two files: manifest.json and background.js Despite the browser (Chrome version 112) not reporting any errors, we are facing an issue where the user agent is not being set to 'my-custom-user-agent&a ...

Looking for a Javascript tool to select provinces graphically?

Looking for a graphic province selector similar to the one found on this website: . If anyone is aware of something like this, especially in the form of a jQuery plugin, that would be fantastic. Thank you. ...

What could be causing the remove attribute API to not function properly only for the "is" attribute?

var divElement = document.createElement("div"); var innerHTMLText = "<div id='issue' is='if'> some content </div>"; divElement.innerHTML = innerHTMLText; document.body.appendChild(divElement); var newDivElement = document.qu ...

Choosing a button value from a form in Selenium: Best practices

I am looking to streamline the process of registering for classes. The snippet of HTML code on the page appears as follows: <form id="SearchClasses" name="selectedStatusForm" action="/more/SearchClasses.action" method=&quo ...

Using the :not selector with links: a guide

I implemented a hover effect for the links on my website. However, I want this effect to be applied to every link except those within a specific div. Sample HTML <div id="menu"> <div class="menu_item"> <a href="index.html" title="Home" tar ...

What could be causing Mathjax to generate multiple copies?

I have integrated MathJax into my application to render MathML. The code snippet below is used to ensure that the MathML is typeset properly: $rootScope.$watch(function() { MathJax.Hub.Queue(["Typeset", MathJax.Hub]); return true; }); However, I ...

Images do not appear on Bootstrap Carousel as expected

I am facing an issue where the images are not displaying on my bootstrap carousel or when I try to display them individually using their class. I am utilizing bootstrap and express for my project. I have verified multiple times that the file path to the im ...

Difficulty encountered with cURL while attempting to submit information to a Gravity Form on an external website

I am managing two DISTINCT websites: Website A: An interactive Wordpress site featuring a Gravity Form. Website B: A separate non-Wordpress site that hosts a basic form - the information collected from this form needs to be transferred to Website A' ...