Looping through Jquery mouse over and mouse out events

I'm a beginner with jquery and I stumbled upon this piece of code that changes the background of a div when you hover over it and revert to the original color on mouse out:

(document).ready(function(){
         $(".t8").mouseover(function(){
             $(".scover8").css("background-color", "rgba(0,24,60,0.60)");
         });
    $(".t8").mouseout(function(){
             $(".scover8").css("background-color", "rgba(0,0,0,0.30)");
         });
    });

While this is working well for one div, I need to apply it to 9 different div's. Instead of repeating the same code block, I would like to use a for loop. I've seen various examples, but I'm struggling to adapt them to my specific case.

Could someone provide assistance with this?

Here is the HTML CODE (repeated 9 times for .t1, .scover1 / .t2, .scover2 etc.):

<div class="t8" onclick="location.href='index.php?page=databank';" style="cursor:pointer;">
           <div class="scover8">
              <h1><a href="index.php?page=databank">Databank</a></h1><br>
              <h2>Download hier beeld & informatie materiaal.</h2><br>
              <h3>Omschrijvingen, Product Foto's etc.</h3>        
           </div>
        </div>

Answer №1

By avoiding code duplication, you can utilize a start with selector:

This selector targets elements that possess a specific attribute starting exactly with a given string.

You can then manipulate its child elements using the find method:

Retrieve the descendants of each element within the current selection, filtered by a specified selector, jQuery object, or element.

Reference: http://api.jquery.com/attribute-starts-with-selector/

Example Code:

$("div[class^='t']").mouseover(function () {
    $(this).find("div[class^='scover']").css("background-color", "rgba(0,24,60,0.60)");
});
$("div[class^='t']").mouseout(function () {
    $(this).find("div[class^='scover']").css("background-color", "rgba(0,0,0,0.30)");
});

View Demo: http://jsfiddle.net/IrvinDominin/ULEu7/

Answer №2

// Execute the following functions
alterElementOnHover(".t8", ".scover8");
changeBackOnMouseout(".t8", ".scover8");

// Define function to change background on hover
Function alterElementOnHover(element, hoverElement){
element.mouseover(function(){
         hoverElement.css("background-color", "rgba(0,24,60,0.60)");
     });
}

// Define function to change background back on mouseout
Function changeBackOnMouseout(element, hoverElement){
element.mouseout(function(){
             hoverElement.css("background-color", "rgba(0,24,60,0.60)");
         });
}

Answer №3

You can easily apply this event to all elements with the same class. Utilize the use of "this" to target the inner element and modify its background color.

It is recommended to update your background using classes rather than inline styling. I have incorporated the .hover() function, which covers both mouseover and mouseout events:

jQuery

$(".t").hover(function () 
{
     $(this).find('.scover').addClass('bgGrey');
}, function()
{
     $(this).find('.scover').removeClass('bgGrey');            
})

Css

.scover
{
    background-color: rgba(0,0,0,0.30);
}

.scover.bgGrey
{
    background-color: rgba(0,24,60,0.60);
}

The default background color is maintained when not hovered over.

jsFiddle


Alternatively, you may achieve this effect using pure CSS. Here's an example.

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

How to iterate over JSON data using jQuery and showcase it in a table

I'm struggling with rendering specific values from a JSON object in a tabular format through looping. I want to create a new row for each instance of data. Check out the CodePen link I've shared below for testing purposes. Any help on what I migh ...

Place the delete and edit buttons on the right side of the card

I am trying to align the edit and delete buttons with the image and premise name on the same line. Both buttons should be placed on the right side and have the same size as the card. Currently, the layout looks like this: https://i.sstatic.net/sNikU.png ...

What are the steps to increase the size of the v-stepper-step in Vuetify?

Is there a way to adjust the size of the icon/step circle in v-stepper? ...

Utilizing Bootstrap and customized JavaScript functions for enhancing form validation

I am in the process of creating a form that includes multiple validation rules for most of its fields. Initially, I utilized Bootstrap form validation because I appreciate its handling of error messages and valid input notifications to the user. This metho ...

substitute a variable

I am trying to update the value of a variable using an HTML form. Within my config.php file, I have declared a variable $num = 3; I would like the value 3 to be replaced with whatever I input in the form form.html. Below is the code for my HTML form : ...

Aligning images in columns

I need help aligning a set of images using CSS. Currently, they are stacked top to bottom and I want them to be placed left to right instead. In simpler terms: 1|2|3|4 5|6|7|8 vs 1|3|5|7 2|4|6|8 #photos { line-height: 0; -webkit-column-count: ...

How can the height of a Material-UI Grid item be dynamically set to match its width?

I am trying to create grid items that are square, where the height matches the width: const App = ({ width, items }) => ( <Grid container> {items.map((v) => ( <Grid item md={width}> // I want this Grid item to be square ...

Learn the steps to update PHP headers on a specific website using AJAX

contactfrm.php <?php // Server side validation $name = $_POST['name']; $surname = $_POST['surname']; $bsubject = $_POST['subject']; $email= $_POST['email']; $message= $_POST['message']; $to = " ...

Troublesome Appearance of Datatables in Bootstrap 4

I've been trying to integrate Datatables with Bootstrap 4, but the end result isn't visually appealing. Even after following the basic example provided on the Datatables site, the table still looks off (refer to the screenshot below). I have inc ...

Clipping of the background image

http://jsfiddle.net/R82a4/ My attempt at achieving the desired result fell short: <div style="background-position: -50%; width: 100%; background-image: url('/assets/upload/stab/1/taccos.png'); background-repeat: no-repeat; background-size: 1 ...

Using Java beans to present form data utilizing session

How can I utilize Java Beans and session beans to store user input data and display a preview of the entered details on the next page? I have already created a servlet using JSP, but now I want to incorporate Java Beans to showcase the form data. How shoul ...

Adding a list of items to a dropdown using the combobox class

Having trouble adding data to a dropdown list using jQuery JavaScript: var options = ''; options += '<option value="0">Select Client</option>'; $.each(result, function(i, result) { options += '<option v ...

Ways to create a scrollable div with the help of Javascript

I am currently developing a web app on the Tizen platform. Within my HTML5 code, I have a div element with an image set as its background. In certain scenarios, I need to display random text within this div multiple times. The text can vary in size and ma ...

Experiencing difficulties with capturing the focus event of the <select> tag

I'm completely stumped at the moment... I just can't seem to get my head around how to make a jQuery $("thing").is(":focus") selector work with a <select> tag in my project. Here's what I've got so far: <input id="uText" name ...

Utilizing an array element within a conditional statement

I am currently working on an analysis to plot a series of values across a range of time values represented by the variable t in an array format. Ux and Uy are functions of t, as are U1, U2, Ep1, and Ep2, due to their relationships. The issue arises at the ...

sending a file to a controller without the use of a form

Hey there, I'm exploring a way to transfer a file from a view to a controller without using a form. My goal is to enable the user to browse for a file and have it sent to the controller via Ajax. Do you think this is achievable? <td>Import ...

Ways to center text vertically using CSS

It appears that certain letters like g, y, q, etc. which have a downward sloping tail, are causing issues with vertical centering. Here is an image illustrating the problem https://i.sstatic.net/Pcnl8.png. The characters inside the green box are perfectly ...

Tips for utilizing an event listener for a submission button

I am encountering a problem with this event listener. I attempted to add an event listener to the submit button, but it seems to be inactive. I can't figure out what mistake I have made! Here is my code: const form = document.getElementById("form") ...

What is the best way to choose specific attributes in CSS?

My website has three large CSS files, each containing many classes. Some of these classes have the same name but are defined in different files. For example: CSS1: ... .btn-primary { background: #000; } ... CSS2: ... .btn-primary { back ...

What is the best way to iterate over a continuous set of data points in a

My data frame is structured like this: > df symbol x1 x2 1 A 3.6 5.2 2 A 10.0 4.8 3 A 5.2 0.2 4 A -10.2 0.4 5 A 5.4 -2.5 6 B 9.9 6.5 7 B 15.8 -1.8 8 B 4.5 -5.9 ...