Function in jQuery to reference two different divs

I'm currently facing an issue with a code snippet that I have. The requirement is for the user to be able to hover over "Div 1" and/or "Div2" and trigger a red border around both elements simultaneously. Due to the complexity of my WordPress theme, these elements cannot be nested, making it challenging to achieve this effect using simple CSS methods.

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="main.css">
    </head>    

<body>
    <div class="attachment-shop_catalog">Div 1</div>
    <div class="title-wrapper">Div 2</div>
</body;

<script>

$(document).ready(function() {
   $('.attachment-shop_catalog .title-wrapper').hover(function() {
   $(this).css('border', '1px solid red');
   },function() {
   $(this).css('border', '0');
   });
});

</script>

</html>

CSS (external stylesheet):

.attachment-shop_catalog {
    background-color: grey;
    border: 1px solid #000;
    border-bottom: none;
    padding: 10px 20px 10px 20px;
    width: 80px;
 }

.title-wrapper {
    border: 1px solid #000;
    padding: 40px 20px 40px 20px;
    width: 80px;
}

Attached are images from the live site showcasing where the red border needs to appear identically on both elements simultaneously.

https://i.sstatic.net/fWAGL.png https://i.sstatic.net/luSAB.png

I would greatly appreciate any guidance or assistance in resolving this issue with the code. Thank you in advance! :)

Answer №1

$(document).ready(function() {
   $('.attachment-shop_catalog, .title-wrapper').hover(function() {
   $('.attachment-shop_catalog, .title-wrapper').css('border', '1px solid red');
   },function() {
   $('.attachment-shop_catalog, .title-wrapper').css('border', '0');
   });
});

Give this a go. This code will add or remove border to both selected divs.

Answer №2

To bind the handler effectively, remember to use a comma to select multiple elements. Additionally, when using a space in a selector, it signifies that the second class must be nested within the first.

If you desire to enclose both DIVs in a single box rather than individually, make sure to wrap them in another parent DIV.

$(document).ready(function() {
  $('.attachment-shop_catalog, .title-wrapper').hover(function() {
    $(this).closest(".container").css('border', '1px solid red');
  }, function() {
    $(this).closest(".container").css('border', '0');
  });
});
.attachment-shop_catalog {
    background-color: grey;
    border: 1px solid #000;
    border-bottom: none;
    padding: 10px 20px 10px 20px;
    width: 80px;
 }

.title-wrapper {
    border: 1px solid #000;
    padding: 40px 20px 40px 20px;
    width: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="attachment-shop_catalog">Div 1</div>
  <div class="title-wrapper">Div 2</div>
</div>

Answer №3

It is assumed that the DOM structure ensures $('.attachment-shop_catalog') and $('.title_wrapper') are congruent, forming pairs despite their physical layout.

If this assumption remains consistent, it should persist even through WordPress DOM changes, allowing for the following javascript implementation:

$(document).ready(function() {
    var pair = '_hover_binding_'; // a unique random string

    $('.attachment-shop_catalog').forEach(function() {
        var $pair = $('.title-wrapper').eq($('.attachment-shop_catalog').index(this)).add(this);
        $pair.data(pair, $pair);
    })
    .add('.title-wrapper').hover(function() {
        $(this).data(pair).css('border', '1px solid red');
    }, function() {
        $(this).data(pair).css('border', '0');
    });
});

This procedure may seem complex but with comprehensive jQuery knowledge, it can be easily understood as per the comments provided.

The initial assumption can be adapted if necessary. Any reliable pairing rule at step 1 will yield a functional solution.

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 a sleek method for including a key and value pair to an object using an array?

In a project using angular2/typescript, I am working with an array of objects that contain key/value pairs from a database. These values are then displayed in a table on the UI using ag-grid-ng2. The table headers are dynamic and set in the database. One ...

Filtering MUI Data Grid by array elements

I am in the process of developing a management system that utilizes three MUIDataGrids. Although only one grid is displayed at a time, users can switch between the three grids by clicking on tabs located above. The setup I have resembles the Facebook Ads ...

Issue encountered with Ionic and ssh2: process.binding is not supported

I am currently delving into the world of Ionic and experimenting with creating a basic application that utilizes SSH2 to establish an ssh connection between the app and a server. Here is a breakdown of the steps I took to encounter the issue: Steps to Rep ...

Dealing with an overflow of Redis clients in NextJS: Simplifying the process with just one client

Introduction Hello there! I have developed a new app for a discord web-dashboard and utilized redis as my database. The main Issue Whenever I send an axios request to one of the documents in the api folder, which requires a redis client, a new redis cl ...

Link to Reply Comment Feature in Wordpress

It seems like I've tried numerous solutions to fix my issue but haven't had any luck, so now I'm seeking help here. Despite trying methods that have worked for others, they do not seem to work for me. My problem lies with nested comments on ...

I am curious as to why the "default + label" pseudo-class is not functioning properly on the "input" element. Specifically, I am having trouble with the "+ label" portion

":default" works fine on its own, but when combined with the "label" pseudo-class, it fails to apply. .pseudo-test input:default { box-shadow: 0 0 20px 20px red; } .pseudo-test input:default+label { color: coral; } <div style ...

When trying to access the key value of a dynamically generated object, it returns as undefined

I am facing a challenge with my student object structure... { Freshmen: [{id: 3}, {id: 5}], Sophomores: [{id: 2}, {id: 6}], Juniors: [{id: 1}, {id: 8}], Seniors: [{id: 9}, {id: 4}, {id: 7}] } My goal is to retrieve full student objects from the d ...

End of ImageButton tag

I am currently working on this code : <div runat="server" class="slide"> <img src="images/picto_detail.gif" onclick='<%# Eval("CampagneRappelId","hideshow(\"details{0}\")")%>' /> <div id='details<%# Eval("C ...

v-for triggers actions on every div

Yesterday I posed a question regarding the removal of a custom truncate filter in Vue. If you missed it, you can find the original question here: Deleting a Vue custom filter when mousing over However, what I failed to mention is that I am utilizing a v- ...

Having trouble accessing Kotlin JS from JavaScript

I'm currently experiencing an issue where I am unable to call any Kotlin JS function and receiving an error stating that 'something' is not defined. Initially, I attempted compiling the project with Gradle but found success after following ...

Is it possible to trigger an event just once?

Is there a way to ensure an event only fires once? I recently discovered that using .one seems to do the trick. ...

Using the 'useMediaQuery' function from Material UI in a class component

Currently experimenting with Material UI's useMediaQuery feature to adjust the styles of a specific component, in this case the Button component. The objective is to eliminate the outline surrounding the button when the screen size decreases. The atte ...

What are the steps to implement email validation, Saudi mobile number validation, and national ID validation in cshtml?

Looking to implement validations for the following fields: email, mobile number (must be 10 numbers and start with 05), and National ID (must be 10 numbers and start with 1 or 2) <input class="form-control" type="text" id="txt ...

What is the best way to set a default function in a mongoose schema?

After spending quite a few hours trying to resolve this issue, I have finally turned to Stack Overflow for help. The problem I'm facing is with the promise pending errors on a specific field where I need to set a default value. Here's the code s ...

The dynamic duo: Selenium and HTML!

For the past few days, I've been using selenium to extract information from a private database of company data. Unfortunately, due to the password protection of the database, I can't share the entire python code or HTML code. Here is the specifi ...

Switching between components in vue.js: A beginner's guide

In my project, I created a Dashboard.vue page that consists of three child components: Display, sortBooksLowtoHigh, and sortBooksHightoLow. The Dashboard component also includes a select option with two choices: "Price: High to Low" and "Price: Low to High ...

Having trouble retrieving the $scope value in HTML, even though it was assigned within the success function of $http.post

Having trouble accessing the values of $scope properties after a successful $http post in index.html file. Here is the code snippet for reference, any help in resolving this issue would be greatly appreciated as I am new to AngularJs var app = angular.m ...

The REST API endpoint links for Timestamp are displaying a 404 error message indicating they cannot be

After recently diving into backend development, I ran some tests locally using Postman and localhost which seemed to work perfectly. However, upon uploading my code to GitHub, I encountered a 404 error when clicking on the API endpoint hyperlinks from inde ...

"Uncaught ReferenceError: $ is not defined in a JavaScript/Vue.js

Currently, I am working on the javascript/vue.js page found at this link. In this file, I have added the following code: $(document).ready(function() { myIP(); }); function myIP() { $.getJSON("//freegeoip.net/json/?callback=?", function(data) { / ...

I require assistance in configuring the timing for an animation using Jquery

How can I adjust the timing (delay between two words) for this animation? If you need help, you can check out this link for guidance. Feel free to share your suggestions! ...