Modify css using jquery for multiple ids assigned to the same class

I have a set of 3 divs all sharing the same class.

<div id="qq1" class="cl">sentence</div>
<div id="qq2" class="cl">sentence</div>
<div id="qq3" class="cl">sentence</div>

I am interested in finding out how to properly write code that will trigger a mouse event for these 3 divs with one function, targeting the 'cl' class and returning the appropriate ID for adjusting CSS properties. For example:

<script>
$('.cl').on('mouseenter', function() {
    var currentId = $(this).attr('id');
    $('#' + currentId).css("background-color", "#99cc33");
    $('#' + currentId).css("color", "white");
});
$('.cl').on('mouseleave', function() {
    var currentId = $(this).attr('id');
    $('#' + currentId).css("background-color", "white");
    $('#' + currentId).css("color", "#404040");
});
</script>

However, there seems to be an issue because it is not functioning as expected.

Answer №1

The variable currentId is not being used at all, instead a string containing the characters c, u, r, etc., 'currentId' is being attempted to be used.

If you want to use the actual variable value, you should write it as $('#' + currentId).css() - for example, if currentId is 'qq1', then you would effectively be saying $('#qq1').css().

However, in this scenario, you can skip using the id altogether by simply using $(this):

$('.cl').live('mouseenter', function() {
    $(this).css({"background-color" : "#99cc33",
                 "color" : "white"});
});

$('.cl').live('mouseleave', function() {
    $(this).css("background-color", "white");
    $(this).css("color", "#404040");
});

When working within a jQuery event handler, this refers to the DOM element itself, while $(this) creates a jQuery object representing that element and allowing you to apply jQuery methods on it. The .css() method accepts multiple properties in map form, enabling you to set them collectively with one call - this syntax is demonstrated in the mouseenter section but not in the mouseleave, so that you can make a comparison.

(Side note: unrelated to your question, but if you are utilizing jQuery 1.7 or later, it is recommended to discontinue the use of .live() as it has been deprecated in favor of .on() - guidance on converting your code is available on the .live() documentation page. If you are operating on versions less than 1.7 but greater than 1.4.2, consider switching to .delegate().)

Answer №2

<script>
$('.cl').live('mouseenter', function() {
    var currentId = $(this).attr('id');
    $('#' + currentId).css("background-color", "#99cc33");
    $('#' + currentId).css("color", "white");
});
$('.cl').live('mouseleave', function() {
    var currentId = $(this).attr('id');
    $('#' + currentId).css("background-color", "white");
    $('#' + currentId).css("color", "#404040");
});
</script>

Make sure to remember to correctly access variables as strings within your jQuery code, using the # id selector and appending the variable for proper functionality.

Answer №3

Instead of the original approach, consider implementing the following:

<script>
$('.cl').on('mouseenter', function() {
    $(this).css("background-color", "#99cc33");
    $(this).css("color", "white");
});
$('.cl').on('mouseleave', function() {
    var currentId = $(this).attr('id');
    $(this).css("background-color", "white");
    $(this).css("color", "#404040");
});
</script>

Answer №4

$(document).ready(function() {
  $('.cl').click(function() {
    var clickedId = $(this).attr('id');

    $("#"+clickedId).css();
  });
});

This code snippet provides a basic concept for handling click events in jQuery. The implementation details may vary depending on specific requirements.

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

Guide on programmatically choosing an option within a variable with the help of jQuery

Imagine having a variable named html, which holds select options like this: var html = '<select>'+ '<option value="10">10</option>'+ '<option value="20">20</option>'+ ...

In search of a highly efficient webservices tutorial that provides comprehensive instructions, yielding successful outcomes

I've reached a point of extreme frustration where I just want to break things, metaphorically speaking, of course. For the past week, I've been trying to learn how to create a web service using C# (whether it's WCF or ASMX, I don't rea ...

Performing a function multiple times by clicking the mouse

I have a function called week(), which provides me with the current first (startDate) and last (endDate) day of the week along with the week number. Additionally, there are two other functions, namely weekPlus() and weekMinus(), containing variables that i ...

The CSS popup box fails to reset its data after being closed, and the closure button does not effectively close the popup

I am having an issue with a login popup on my website. Whenever I fill in the login or registration information and then close the popup, the next time I open it, the input box still contains the previous data. How can I reset the popup to always open with ...

The jQuery AJAX function encountered an error with the following details: "readyState" is 0, "responseText" is empty, "status" is 0, and "statusText" is "error"

I am attempting to make an ajax request: $.ajax({ type: "post", url: "download.php", error: function(data, status, err){ alert(JSON.stringify(data)); }, data: "fileid="+fileid }); This request triggers an alert showing "{"read ...

Aligning images with absolute CSS to text that is wrapping positions the images perfectly alongside the text content

My webpage has a long content section that resizes based on the browser width. Here's an example: <h1 id="loc1">Title</h1> <p>bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bod ...

Update the notification header count in Yii2 without the need to reload the page, ensuring that notifications are automatically refreshed every

Whenever I send a notification from my frontend to backend, I find myself having to reload the page to receive any new notifications. Additionally, every time I read a notification, the count disappears until I reload the page again. How can I change the s ...

Refining to Showcase One Menu Selection

I am having an issue with my bootstrap menu that includes a search field. The problem is that when I try to filter the dropdown menu using the search field, it filters all dropdown items instead of just the one I want. For example, if I search for a term f ...

What is an alternative method for creating a horizontal line without the need for the <hr> tag?

Is there a way to create a slim horizontal line without using the <hr> tag ? This is what I attempted: .horizontal-line{ border-top: 1px solid #9E9E9E; border-bottom: 1px solid #9E9E9E; } While it does function, I am hoping for a thinner line. ...

Tips on adjusting video to the screen size

I am looking to create a fullscreen video for my webpage. I originally used an image as a cover, but now I want to switch to using a video. You can check out my old code on this link. Below is my new video code: <div class="embed-responsive embed-resp ...

How can the text from the title tag be extracted and shown as on-page content in an HTML website? - WordPress

I am currently working on a website with various URLs that all have the same design. My goal is to display unique titles on each page while keeping everything else consistent. I attempted to achieve this using the following code: <script type="text/jav ...

Issue with EventDrop and EventResize functionality in ROR4

I've got some js.coffee code located at http://pastebin.com/U3Mc8ZW6. This controller code can be found here: http://pastebin.com/chrYLga6 And here's the Model code: http://pastebin.com/n9fjt7ds Whenever I try to resize or drag an event, the d ...

Moving from one page to another

I am attempting to create a transition effect between sections within a single-page application. All the sections are contained on the same page, with only one section displayed at a time while the rest are set to display none. When a specific event is tri ...

Loading dynamic fonts in React MaterialUI

In our web application, each user experiences a unique style with colors, fonts, border widths, and more based on the Material UI JSON theme retrieved from the database upon loading the app. The challenge lies in handling dynamic fonts. What approaches ha ...

Pausing for the completion of AJAX calls within a $.each loop before proceeding with the function execution

I am looking to trigger a function only once all of the AJAX calls within my $.each loop have finished executing. What is the most effective approach to accomplish this task? function recalculateSeatingChartSeatIds() { var table_id = $(".seatingChar ...

Skewed div with a stylish background image

Struggling with an issue here. I've managed to skew my div just right, but now I'm trying to get the image to fit without tiling. If anyone can offer some assistance, that would be greatly appreciated. This is what I'm aiming for: https://i ...

Utilizing JSON Data with JQuery: A Beginner's Guide

I am using a setTimeout function to reload another function every 5 seconds. The update_list function is responsible for rendering entrances in a view. However, when there are many entrances and you have scrolled down, the list empties and reloads every e ...

A more efficient method for transforming HTML/CSS into images

I'm in the process of developing a web application that allows users to easily create advertising banners. With this tool, users can add various elements onto a banner such as text, images, and boxes by simply dragging and dropping them onto the canva ...

Validate fields by iterating through an object and considering three data points for each field

The struggle is real when it comes to coming up with a title for this question. Suggestions are welcomed! When it comes to field validation, I require three data elements per field: variable name, element ID, and whether it is required or not. Although I ...

Currently dealing with a script that utilizes AJAX GET to incorporate JSON data into my table

Greetings and thank you for taking the time to read this! Within my HTML, I have implemented a form element that allows inputting data into 5 different fields. This data is then transmitted to a database using my unique API key. Once stored in the database ...