Adding a class to unhovered elements with jQuery/JS: a step-by-step guide

I have a variety of elements that are almost working how I want them to.

There are four divs in total. Depending on the URL visited, I want a specific div to be fully transparent/active. The next div in line should animate in and out of transparency simultaneously, encouraging the viewer to navigate to the next page. Additionally, there is a hover state so that when any of the divs are hovered over, that particular one should become fully transparent too.

I'm running into some confusion when trying to prioritize the hover state rule. When any div is hovered over, I want all other animations to stop, the hovered div to become fully opaque, and the remaining 3 divs to fade to half opacity, regardless of the current page.

Below is my code, feel free to ask if you have any questions. Thank you! You can also view a demo on CodePen: https://codepen.io/summeropratt/pen/LYpoVYg

HTML

<div class="parent">
  <div class="child div1">
    <h2>Div 1</h2>
  </div>
  <div class="child div2">
    <h2>Div 2</h2>
  </div>
  <div class="child div3">
    <h2>Div 3</h2>
  </div>
  <div class="child div4">
    <h2>Div 4</h2>
  </div>
</div>

CSS

.child {
  opacity: .5;
  transition: .2s;
}
.full-transparency {
  opacity: 1 !important;
  cursor: pointer !important;
}
.click-me-next  {
  animation-name: click-me-next;
  animation-duration: 2s; 
  animation-timing-function: ease-out; 
  animation-delay: 0;
  animation-direction: alternate;
  animation-iteration-count: infinite;
  animation-fill-mode: none;
  animation-play-state: running;
}
@keyframes click-me-next{
  0% {
    opacity: .5;
  }
  100% {
    opacity: 1;
  }
}

JS

// if(window.location.pathname == '/div3-url/') {
  var opacity = $(".div3").css("opacity");
  console.log("opacity", opacity);
  $(".div3").css("opacity", 1);

  var div4 = document.getElementsByClassName("div4")[0];
  div4.classList.add("click-me-next");
// });

$(".child").hover(function() {
    $(this).addClass("full-transparency");
  }, function() {
    $(this).removeClass("full-transparency");
});

Answer №1

Enhance your CSS selector by adding a class and then dynamically switching it on hover using jQuery's add and remove functions.

$(".child").hover(
  function() {
    $(".child").each(function(i, el) {
      $(el).addClass('hover')
    })
  },
  function() {
    $(".child").each(function(i, el) {
      $(el).removeClass('hover')
    })
  }
)
.child {
  opacity: .5;
  transition: .2s;
}

.full-transparency {
  opacity: 1 !important;
  cursor: pointer !important;
}

.full-transparency.hover {
  opacity: .5 !important;
}

.click-me-next.hover {
  opacity: 1 !important;
  cursor: pointer;
}

.click-me-next {
  animation-name: click-me-next;
  animation-duration: 2s;
  animation-timing-function: ease-out;
  animation-delay: 0;
  animation-direction: alternate;
  animation-iteration-count: infinite;
  animation-fill-mode: none;
  animation-play-state: running;
}

@keyframes click-me-next {
  0% {
    opacity: .5;
  }
  100% {
    opacity: 1;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div class="child div1">
    <h2>Div 1</h2>
  </div>
  <div class="child div2">
    <h2>Div 2</h2>
  </div>
  <div class="child full-transparency div3">
    <h2>Div 3</h2>
  </div>
  <div class="child click-me-next div4">
    <h2>Div 4</h2>
  </div>
</div>

Answer №2

One issue is that you need to revert back to the previous state when hovering out. The simplest solution is to introduce additional classes and toggle them based on the hover state, considering the order of these classes.

I included a class (click-me-next-pause) to halt the animation, and two classes (current-active) and (current-active-transparent) for state transition.

The use of the `!important` keyword is unnecessary since the sequence of classes holds significance.

Take a look at the code snippet below:

// if(window.location.pathname == '/div3-url/') {
  var opacity = $(".div3").addClass("current-active");
  
  var div4 = document.getElementsByClassName("div4")[0];
  div4.classList.add("click-me-next");
// });

$(".child").hover(function() {
    $(".click-me-next").addClass("click-me-next-pause");
    $(".current-active").addClass("current-active-transparent");
    $(this).addClass("full-transparency");
  }, function() {
    $(this).removeClass("full-transparency");
    $(".click-me-next").removeClass("click-me-next-pause");
    $(".current-active").removeClass("current-active-transparent");
});
.child {
  opacity: .5;
  transition: .2s;
}
.current-active
{
  opacity: 1;
}
.current-active-transparent
{
  opacity: 0.5;
}
.full-transparency {
  opacity: 1 ;
  cursor: pointer;
}
.click-me-next  {
  animation-name: click-me-next;
  animation-duration: 2s; 
  animation-timing-function: ease-out; 
  animation-delay: 0;
  animation-direction: alternate;
  animation-iteration-count: infinite;
  animation-fill-mode: none;
  animation-play-state: running;
}
.click-me-next-pause{
  animation-iteration-count: 0 ;
  animation-play-state: pause ;
}
@keyframes click-me-next{
  0% {
    opacity: .5;
  }
  100% {
    opacity: 1;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <!-- first child -->
  <div class="child div1">
    <h2>Div 1</h2>
  </div>
  <!-- second child -->
  <div class="child div2">
    <h2>Div 2</h2>
  </div>
  <!-- third child -->
  <div class="child div3">
    <h2>Div 3</h2>
  </div>
  <!-- fourth child -->
  <div class="child div4">
    <h2>Div 4</h2>
  </div>
</div>

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 the best way to divide a pair of words onto two lines individually?

Looking for a way to break the word 'Mon 24' into separate lines like this: Mon 24 I attempted using word-break: break-all without success. Check out my code example here: https://codepen.io/bbk_khadka/pen/zbVLEp ...

Tips for evenly and fully stretching a set number of horizontal navigation items across a designated container

I want to evenly distribute 6 navigation items across a 900px container, with equal amounts of white space between each item. Here is an example: ---| 900px Container |--- ---| HOME ABOUT BASIC SERVICES SPECIALTY SERVICES OUR STAFF CONTACT ...

Issue with ChartJs version 2.8.0: The custom tooltip remains visible even when clicking outside the chart canvas or moving the mouse pointer

I am utilizing ChartJs to display a line chart with a custom tooltip that appears upon the click event of the data points. The challenge I am facing is that the custom tooltip remains visible even when the mouse pointer is outside the chart canvas area. ...

Retrieve the visitor's IP address following the submission of an AJAX form

Currently, I am facing an issue with my HTML form and JavaScript method integration. Whenever a visitor submits the form, a JavaScript method is triggered which sends an AJAX request to a PHP file on my server. The problem arises when trying to retrieve ...

Attempting to Send an Ajax Request and Utilize the Result within a React Component

I am having issues with my tweet box component. I have a submit function that triggers the getAllTweets function when called. The problem is that I am unable to capture the value of the field and pass it on to the getAllTweets function in order to create ...

Next.js experiences slowdown when initializing props on the server side

I've been working on implementing SSR with Next.js. In my code, I'm fetching JSON data and using them as initial props. Everything works fine in development mode, but when I deploy to the server, fetching only works on the client-side (when navi ...

The total value of elements that are constantly changing

Is there a way to calculate the real-time sum of dynamic elements' values, but I seem to be struggling with it. Check out my DEMO here. Here is the code snippet I am using: My Javascript code: <script> $(document).ready(function(){ ...

Three.js - Model is unable to cast shadows

Greetings! I am currently diving into the world of three.js and utilizing react-three-fiber to integrate it with React. However, I've encountered a challenge regarding shadow casting between models. Despite setting obj.castShadow = true and obj.receiv ...

jQuery script located on local server fails to function

After downloading the jQuery.js file from jQuery.com, I made sure to save it in multiple locations - including JRE/Lib and my desktop where the HTML file that calls it is located. The script reference looks like this: <head> <script type= ...

Incorporating a requirement into a function to ensure it is executed only under certain circumstances

I'm currently developing a text-based game using JavaScript that involves picking up a sword with the help of an in-game function. var takeSword = function() { if (currentRoom.hasSword) { $("<p>You picked up a sword.</p&g ...

Is there a way to vertically align the content of two <li> elements when one contains an image within an anchor tag?

I'm attempting to display an HTML unordered list horizontally with each item having the same length and height, while also containing a link. One of the items should also contain an image. My goal is to align these items vertically. To achieve this, ...

Guide on exporting data from ejs files to a pdf file using pdfkit in a node js environment

Below is the code from my result.ejs file: <div style="width: 50%; margin: auto;"> <table class="table"> <thead> <tr> <th>SUBJECT</ ...

Exploring the functionality of Vue.js through Jasmine without the use of JavaScript modules

My task involves investigating unit testing for JavaScript on an older application that does not utilize JS modules (import/export). The app contains JS object/prototypes in external .js files that are imported via script src, and more recently, some Vue 2 ...

Updating Angular 8 Component and invoking ngOninit

Within my main component, I have 2 nested components. Each of these components contain forms with input fields and span elements. Users can edit the form by clicking on an edit button, or cancel the editing process using a cancel button. However, I need to ...

Adding LocalStorage functionality to buttons in order to switch colors can be done by storing the

I've run into an issue trying to incorporate LocalStorage with the buttons that change colors as themes in JavaScript. I'm new to coding and eager to add this feature to my personal blog. $(document).ready(function () { $(".header--theme-button ...

including a comma in the jQuery counter

We are facing a challenge with our animated counter. Currently, it counts up quickly to a number without commas for thousands. Despite being well-versed in this area, we are struggling to implement the comma feature. Our existing code functions perfectly ...

Is it possible to center content with Bootstrap?

Is there a different method to center content with empty space on either side? For instance: <div class="col-md-3"></div> <div class="col-md-6"> <div class="form-group"> .... </div> </div> <div class="col ...

Troubleshooting bitrate and quality issues in AWS MediaConvert

Whenever I attempt to initiate a MediaConvert job in CBR, VBR, or QVBR mode with Bitrate or MaxBitrate exceeding 250,000, an error occurs. The message reads: "Unable to write to output file [s3:///videos//***/original.mp4]: [Failed to write data: Access D ...

Steps for selecting a radio button based on a MySQL table value:

My table has two fields, name and gender. When I retrieve the data and attempt to display it in input fields, everything works fine for the Name field. However, I am curious if there is a way to automatically select the radio button based on the gender d ...

Utilizing Vue's string-based class binding feature?

Can Vue class binding work with strings? For example: <div :class={open: target == 'myString'}></div> var app = new Vue({ target: null }) It works when I don't use quotes <div :class={open: target == myString}></div ...