jQuery fails to hide DIVs when jQuery.show() has been utilized in a previous event

I've always considered myself pretty proficient in jQuery, but this particular issue has me stumped. Essentially, I have a click event that should hide one DIV (a placeholder) and show two others (an input section and control buttons section). However, when I attempt to change the main displayed DIV by clicking on one of the control buttons (which involves hiding all DIVs and showing the desired one), the hide() function doesn't seem to work as expected.

It's a bit tricky to articulate, so I've created a jsFiddle to demonstrate the problem: jsFiddle

In the jsFiddle, the intended behavior is for clicking "CLICK ME" to arrange the DIVs correctly. Subsequently, clicking on boxes 1, 2, or 3 should change the text to "Item 1," "Item 2," or "Item 3." However, you'll notice that the "Item 1" DIV isn't hidden because it was initially shown during setup. Commenting out line #5 in the JavaScript resolves the issue, although it compromises the initial layout (I prefer "Item 1" to be displayed by default).

Of course, this example is greatly simplified compared to my actual project.

Has anyone encountered this issue before and determined its cause?

Here's some code:

HTML:

<div id="newinput">
<div class="inputmode">
    <div class="placeholder">CLICK ME</div>
    <div class="modeitem item1">Item 1</div>
    <div class="modeitem item2">Item 2</div>
    <div class="modeitem item3">Item 3</div>
</div>
<div class="controls">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
</div>

JavaScript:

$('#newinput').click(function () {
    var im = $(this).children('.inputmode');
    var ph = im.children('.placeholder').html();
    im.children('.placeholder').hide();
    im.children('div.item1').show();
    $(this).children('.controls').show();
});

$('#newinput .controls .item').click(function () {
    var item = 'item' + $(this).html();
    var im = $('#newinput').children('.inputmode');
    im.children('div').hide();
    im.children('.modeitem.' + item).show();
});

Answer №1

The reason behind this behavior is event propagation. When the .item element is clicked, it also triggers the click handle for #newinput.

To resolve this issue, assign the first handler only to the placeholder element.

$('#newinput .inputmode .placeholder').click(function () {
    var im = $(this).closest('.inputmode');
    var ph = im.children('.placeholder').html();
    im.children('.placeholder').hide();
    im.children('div.item1').show();
    im.next('.controls').show();
});

$('#newinput .controls .item').click(function (e) {
    var item = 'item' + $(this).html();
    var im = $('#newinput').children('.inputmode');
    im.children('div').hide();
    im.children('.modeitem.' + item).show();
});

Check out the demo: Fiddle

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

Permit the use of HTML tags within a CSS-only tooltip

I have created a unique CSS tooltip. <span data-tooltip="The security code is a 3-digit number<br />on the back of your Visa or Mastercard debit or credit card, or a 4-digit number on the front of your American Express card.">Help</span> ...

Encountering a 404 error while loading CSS in a Django application

I'm currently in the process of developing a chatbot application. I'm encountering issues with loading the CSS for the frontend using django's static data load feature. Here are the file paths: CSS path: C:\Documents\Django_Works ...

Is there a way to prevent mouse wheel scrolling on a React "number" input field?

Currently, I am encountering an issue with MUI type="number" textfields. When I focus on the field and then scroll the mousewheel, the input value changes unexpectedly. I have looked into adding a blur function after scrolling to prevent this, but I would ...

Troubles with DropDownList onChange event when selectedIndex is at 0

Hey there, I have a question that's been puzzling me. I have three security question dropdown menus on my ASPX page with JavaScript that removes and repopulates questions based on user selection. Everything works great when editing an existing profile ...

NextJS able to execute code on the client side after being called from the server side

I am currently using getStaticProps to retrieve data from the server at build time and pass it to my page component. The following call is made from my page component file: const getStaticProps: GetStaticProps = async (context) => { const pa ...

Having difficulty retrieving data from JSON file using Backbone framework

When I click on the div, I am attempting to retrieve JSON data but am unable to view the output. I am utilizing Backbone Collection to fetch JSON data. I have tried displaying the JSON data in the console as well as within another div. The contents of the ...

Positioning a div on the right side of its parent div

Hi there! I'm currently working on a small navbar that has two sections: the left section with an arrow icon and the right section with two icons - an envelope and an exclamation triangle. I've been trying to position the right section in the top ...

An issue occurred when attempting to integrate Angular

Currently, I am in the process of learning AngularJS. To practice, I attempted a simple code snippet in an HTML file: <!DOCTYPE html> <html lang="en" ng-app=""> <head> <meta charset="utf-8"> &l ...

What is the reason for needing a page reload in Javascript or JQuery?

I'm curious why Javascript or jQuery require a page reload before applying certain effects. CSS updates in real-time, as demonstrated by the following example: This changes dynamically without needing to refresh the page @media all and (max-width:7 ...

Discovering the world of Javascript and JQuery by diving into the intricacies of

Similar Question: Formatting dates using Javascript I have recently started working with JavaScript and jQuery. I am currently experimenting with creating a page that retrieves data from a public Google calendar and displays the events, including star ...

The JQuery/Ajax script only loads once in the HTML document

I'm currently working on a webpage that displays data from two databases almost instantaneously. However, I've encountered an issue where my JQuery Ajax call only updates the HTML content once. HTML Code: <div class="database"> ...

Laravel 8 - sweet alert functions properly, however, the ajax functionality is not functioning as expected

As a newcomer to Ajax, I am facing an issue with deleting records from the database using Sweet Alert2. Although my swal is working fine, the ajax function seems to be malfunctioning. Can anyone point out where the problem might be and suggest a solution? ...

What is the best way to extract data using Angular from the backend and then transfer it to the frontend using Node.js?

Recently, I decided to make a change in my node.js application. Previously, I was using the EJS template engine but now I want to switch to Angular. To do this, I have already installed Angular and it is working well. However, I am facing an issue while t ...

The Unexpected Mishaps of CSS Grid Layout

I attempted to create a grid using CSS, but I seem to have made an error somewhere in my code. Can someone please take a look at my jsFiddle link and provide some guidance? jsFiddle /*Grid*/ .container { width: 100%; max-width: 1200px; } .row:before, ...

Pass a reply from a function to a route in expressjs

I'm currently working on a project where I need to retrieve JSON data from an API using an Express server in Node.js. However, I'm facing some confusion regarding how Node.js manages this process. In my code, I have both a function and a route de ...

AngularJS Service Implementing the Pub/Sub Design Pattern

I've been browsing for solutions to a problem and stumbled upon an answer provided by Mark Rajcok angular JS - communicate between non-dependend services However, I am struggling to fully grasp his explanation, particularly this part: angular.forEa ...

Always take the lead with the first image in navigation

Looking to add an image to your website navigation? Want the image to appear at the beginning of the navigation bar, before Link 1? Here's a bit of CSS code for you: <div class="topnav"> <img src="https://cdn.mos.cms.futurecdn ...

Assign a unique HTML attribute to a child element within a Material-UI component

Currently, I am trying to include the custom HTML5 attribute "data-metrics" in the span element within the ListItemText Material UI component. However, I am facing some difficulty achieving this as per the specifications outlined in the Component API Docum ...

Lock GridView headers when only scrolling vertically

I am facing an issue with my gridview on an aspx page. The gridview is wider than the page itself, so I want the headers of the gridview to scroll horizontally along with the content, while remaining fixed vertically. Can anyone help me achieve this? I hav ...

Send a request to the uClassify API using the Node request module

I'm currently working on integrating the uClassify API into my Node project, but I'm encountering some issues with my code. Here's what I have so far: const req = JSON.stringify('Hello, my love!'); const options = { body: ...