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.

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

Webpack is failing to recognize certain CSS files

My development stack includes Vue.js 2.5.15, Webpack 4.12.0, css-loader 0.28.11, ASP.Net Core 2.1 in Visual Studio 2017. Starting with the Visual Studio asp.net core template project for Vue and Typescript, I prefer to have individual small CSS files with ...

The JSP page does not redirect after an Ajax post request has been made

When submitting a form with basic AJAX post, I am facing an issue where the redirection to the JSP does not occur upon success. Setting the redirect programmatically seems to create a new JSP instead of utilizing the existing one with POST data. After debu ...

What is the definition of a type that has the potential to encompass any subtree within an object through recursive processes?

Consider the data structure below: const data = { animilia: { chordata: { mammalia: { carnivora: { canidae: { canis: 'lupus', vulpes: 'vulpe' } } } } }, ...

Tips for using the deferred method in ajax to enhance the efficiency of data loading from a php script

I recently discovered this method of fetching data simultaneously using ajax. However, I'm struggling to grasp the concept. Can someone please explain how to retrieve this data from a PHP script and then add it to a div similar to the example provided ...

Every time Tailwind compiles, it seems to generate a glitchy class

There was a time when I accidentally wrote 2 classes without a space max-w-[412px]mb-[36px]. This caused an error, so I added a space between the classes. However, the error persisted even after making this correction. In a last attempt to resolve the issu ...

Scrolling seamlessly within a container that is fixed in position

For hours, I've been attempting to incorporate smooth scrolling into my project with no success. The issue lies in the container where the anchor tags are located. If it's set to fixed position or absolute, none of my attempts seem to work. In ...

The process of uploading data onto a map using jquery is quite inconsistent in its functionality

HTML Instructions: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width,initial-scale=1"> <me ...

Exploring the properties of individual Vue components on a single page with v-for loop

Struggling to render a Vue component in a Rails app by iterating through an array of data fetched via Ajax. The Slim template (index.html.slim) for the index page includes a custom_form_item component, where items represent custom forms data from Rails and ...

Refresh the page to verify if the user has successfully established a connection with PhoneGap through AngularJS

I am currently developing an app using PhoneGap. I have successfully implemented a feature to check if the user is connected to the internet or not. However, if the user is not connected, I would like to provide a button for them to click on in order to re ...

Collapsing or expanding the Material UI accordion may lead to flickering on the page

import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import Accordion from "@material-ui/core/Accordion"; import AccordionDetails from "@material-ui/core/AccordionDetails"; import Accordi ...

Is there a way to make images appear on the screen only when they come into view on

While exploring the internet, I came across something quite intriguing on a website: As you scroll down the page, images only load when they come into view in the browser window. This is a feature I have never seen before and I am curious if anyone else h ...

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

Canvas not displaying image in JavaScript

I have a bird object with a draw function defined, but for some reason, the image is not showing up when called in the render function. Can someone please help me figure out what I'm doing wrong? Thanks in advance. EDIT: Upon further investigation, I ...

Error: Unable to locate Buffer2

I encountered the error Uncaught TypeError: Buffer2 is undefined when trying to import jsonwebtoken into my React project. The errors occur with both import jwt from jsonwebtoken and import {decode} from 'jsonwebtoken'. My versions are jsonwebt ...

The issue arises when trying to use jQuery on multiple elements with the same class

Recently, I came across a jQuery script for my mobile menu that changes the class on click event. jQuery("#slide-out-open").click(function() { if( jQuery( this ).hasClass( "slide-out-open" ) ) { jQuery('#wrapper').css({overflow:"hidd ...

Transforming a JSON into a JavaScript object using deserialization

Within a Java server application, there exists a string that can be accessed through AJAX. The structure of this string is exemplified below: var json = [{ "adjacencies": [ { "nodeTo": "graphnode2", "nodeFrom": "graphnode1" ...

submitting a collection of hashes to a server using jQuery

I'm facing an issue with sending data to the server. I have an array structured like this: places = new Array(); places.push({name: "ci", loc: "bo"}) places.push({name: "ae", loc: "ea"}) if I try to send this data to the server using the following J ...

Angular: Display an element above and in relation to a button

Before I dive in, let me just mention that I have searched extensively for a solution to my problem without much luck. The issue is describing exactly what I'm trying to accomplish in a way that yields relevant search results. If you're interest ...

Instructions on incorporating domains into next.config.js for the "next/image" function with the help of a plugin

Here is the configuration I am currently using. // next.config.js const withImages = require("next-images"); module.exports = withImages({ webpack(config, options) { return config; }, }); I need to include this code in order to allow images from ...

Previewing multiple images with multiple file inputs

I am trying to find a way to preview multiple images uploaded from different inputs. When the button is pressed, the content from a textarea containing <img src="$img" id="img1"> is written inside a div called seeimg. The IDs for these images range f ...