Activate each division separately with a single script

I am facing an issue where each blue div (

<div id="rectangle"></div>
) is not firing independently when hovered or clicked.

Currently, when I hover/click over the first one, both fire simultaneously. However, if I hover/click over the second one, neither fires.

I have tried various solutions from other sources but none seem to work with this specific code. I was hoping someone could provide me with a detailed explanation so I can learn and compare it to the methods I have already attempted.

$('.rectangle1').hide();
          $('#rectangle').on('click', function() {
            clicked = !clicked;
          });

          $('#rectangle').hover(function() {
            $('.rectangle1').slideDown()
          },function() {
            if (!clicked) {
              $('.rectangle1').slideUp()
            }
          });  
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <div id="rectangle"></div>
        <div class="rectangle1"></div>

        <div id="rectangle"></div>
        <div class="rectangle1"></div>

http://jsfiddle.net/Q5cRU/99/

Answer №1

One issue that arises is the duplication of the id="rectangle" attribute for two different elements. As stated on MDN:

The id global attribute specifies a unique identifier (ID) that must be distinct within the entire document.

With jQuery, only the first element bearing this ID will have event listeners added to it.

Answer №2

It's quite simple really: The event listener was only assigned to the initial #rectangle. jQuery does not recognize multiple elements with the same #ID. Therefore, it is not recommended to use identical id attributes for different elements.

For your reference, here is what you are searching for: http://jsfiddle.net/Q5cRU/116/

$(document).ready(function() {

    $('.rectangle1').hide();

    $('.rectangle').data('clicked', false).click(function() {

       $(this).data('clicked', !$(this).data('clicked'));

    }).hover(
      function() {

        $(this).next('.rectangle1').slideDown();

      },
      function() {

          if (!$(this).data('clicked')) {

             $(this).next('.rectangle1').slideUp();

          }
      }
    );  
});

$("div.rectangle1").mouseover(function() {
  $(this).stop(true, true).show();
});

Answer №3

When working with HTML, it is important to remember that the id attribute should be unique for each element. If you want multiple elements to share the same styling or purpose, you can use the class attribute instead. For example, if you have two divs and want them to trigger events independently, make sure to give them different ids - they cannot both be named "rectangle". Feel free to check out this resource for more information on attributes in HTML.

Answer №4

HTML:

<div>
    <div class="box"></div>
    <div class="box-hover"></div>
</div>

<div>
    <div class="box"></div>
    <div class="box-hover"></div>
</div>

CSS:

.box {
   width: 140px; 
   height: 80px;
   background: #037CA9;
  margin-bottom:10px;
}

.box-hover {
   width: 140px; 
   height: 150px;
   background: red;
}

Javascript:

$(function(){

    var clicked = false;

    $('.box-hover').hide();

    $('.box').hover(
        function(){
            $(this).parent().find('.box-hover').slideDown();
        },
        function(){
            if (!clicked) {
                $('.box-hover').slideUp()
            }
        }
    );

});

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

Something strange happening with the HTML received after making a jQuery AJAX request

My PHP form handler script echoes out some HTML, which is called by my AJAX call. Below is the jQuery code for this AJAX call: $(function() { $('#file').bind("change", function() { var formData = new FormData(); //loop to add ...

Fade effect on vectorial HTML map with Javascript (mouseover)

I am trying to add a fade in and fade out effect to my image switching function, but I have not been able to adapt other fade methods into mine successfully. Do you have any suggestions on how I can achieve this? Here is an example of what I currently ha ...

Optimal method for linking jQuery ajax requests to transfer data

Handling several asynchronous ajax calls in a specific order with information passing between them can be quite challenging. The current approach, even with just three API calls, can be cumbersome. Trying to manage five API calls makes it nearly impossible ...

Error: The program encountered a type error while trying to access the '0' property of an undefined or null reference

I am a beginner in the world of coding and I am currently working on creating an application that allows users to add items to their order. My goal is to have the quantity of an item increase when it is selected multiple times, rather than listing the same ...

How to use $$[n] in Spectron/WebdriverIO to target the nth child element instead of the selector

Attempting to utilize Spectron for testing my Electron application has been challenging. According to the documentation, in order to locate the nth child element, you can either use an nth-child selector or retrieve all children that match a selector using ...

Troubleshooting Node Commands malfunctioning following NodeJS update

I have encountered an issue while trying to update my node version. I deleted the nodejs file from the ProgramFilesx86 folder and then used the Windows installer to install the latest version. However, when I attempt to initialize a node project or use npx ...

Exploring data elements in a Javascript array

Is there a way to use Javascript or jQuery to address the individual employee number, tasks, and sites in the following JSON array? $.each(mySchedule, function(i, obj) { console.log(obj.employees); }); var mySchedule = { "schedule": { "empl ...

Integrating CP-ABE into a Node.js and blockchain initiative

Having trouble locating a JavaScript library that supports CP-ABE (Attribute-Based Encryption) for my project. Any recommendations or assistance in finding a suitable solution would be greatly appreciated! Hoping to come across a compatible library ...

I am experiencing difficulty with loading the local images stored in the /public/images directory of my React app

I am currently working on a component called Portafolio.js where I am utilizing the map function to retrieve each object from a file named "trabajos.js" that contains all the objects with their respective properties. My goal is to display an image for each ...

Creating a protected pathway using postMessage within an IFRAME for secure communication

Below is an overview of our application. The user interface is sourced from a secure domain , and scripts are hosted on the same domain. The application loads content from the client site within an IFRAME. Due to concerns about trustworthiness, as the co ...

Encountering invalid parameters while attempting to utilize the track.scrobble service from the Last.Fm API in a Node.js application

After successfully completing the Last.Fm authentication process following the instructions provided here, I received the session key without any issues. However, my attempts to make an authenticated POST request to the track.scrobble method of the Last.Fm ...

Creating a conditional npm script that depends on the output of another: a step-by-step guide

I've encountered this problem before while setting up npm scripts, and I haven't been able to find a solution yet. I'm hoping to make the solution compatible with both Mac and Windows environments. I'm working on splitting up the logic ...

Node JS post route experiencing issues with updating variables within function

I'm in the process of developing an online salon booking system. My goal is to prevent a booking from being made if the salon already has an appointment booked for that day and if the user attempting to make the booking also has an appointment booked ...

The TypeScript inference feature is not functioning correctly

Consider the following definitions- I am confused why TypeScript fails to infer the types correctly. If you have a solution, please share! Important Notes: * Ensure that the "Strict Null Check" option is enabled. * The code includes c ...

JS Code from a JS Fiddle failing to run in a web browser examination

I have been experimenting with a fantastic Expand/Collapse JavaScript function that I came across on JS Fiddle, but unfortunately, it's not working as expected when testing it in a browser. Can anyone provide some guidance on what might be causing the ...

Generate visual content from written text with the use of a form and store it on the

Struggling to implement a php function on my webpage that generates an image from text input. However, nothing appears to be happening when I execute the code: PHP - $to = $paths. '/card.png'; if (isset($_POST['make_pic'])) { $text = ...

CSS lacks hover effects for smooth transitions on mouse over and mouse out

When scrolling down, I've added a transition effect to smoothly change a div element. However, I want to avoid this transition effect when hovering over or moving the mouse out as the div is acting as a button. While I was successful in removing the e ...

Canceling the http post request while subscribing to a service

After wrestling with this issue for a whole week, I am still unable to successfully send a basic post request to the Heroku server using Angular HttpClient. I've meticulously defined all the services in the provider section of the main app module. Str ...

Displaying live data from an XMLHttpRequest in a Vue component in real-time

I'm currently working on implementing lazy loading for a list of posts fetched from the WordPress REST API. My goal is to load additional news stories upon clicking an HTML element. However, I'm facing issues with accessing the original Vue inst ...

Several purposes for eventListener Callback

Within the layout is an html table and span element. The goal is to have the values of value1 and value2 on each row added together and displayed in the sum cell of that same row. Additionally, all the values for value1, value2, and Sum in both Row 1 and R ...