Removing a jQuery class while simultaneously adding it to different elements

I am currently working on a webpage where I have a row of 6 images. The first image, when the page loads, undergoes transformations using CSS3 due to a specific class applied to it. When the user hovers over the other images in the line, the same class is applied to them as well, and then removed once the mouse moves away. However, I now need to implement a feature where if any other image is hovered over, the class is removed from the first image. If no images are being hovered over at all, the original class should be re-applied to the first image.

Below is my current progress with the code:

$(document).ready(function() {
    $("#imagePackshot li img").hover(function(){
        $(this).addClass('packshot').siblings().removeClass('packshot');
    },
    function () {
        $(this).removeClass('packshot');
    })
    .first().addClass('packshot');
});

Answer №1

It is important to verify that there are no other images with the 'packshot' class after removing it, and if so, add it to the first image.

 $(document).ready(function() {
        var activeClass = 'packshot', images = $("#gallerySlideshow li img");
        var first = images.first().addClass(activeClass);
        images.hover(function(){
            // remove the class from all images who still have it, most likely only one.
            images.filter("."+activeClass).removeClass(activeClass); 
            // add class to the element that was hovered.
            $(this).addClass(activeClass);
        },
        function () {
            // remove class from the image that was hovered out of
            $(this).removeClass(activeClass);
            // if no other images have the active class, then give it to the first image
            if(!images.filter("."+activeClass).size()){
               first.addClass(activeClass);
            }
        })
  });

Edit:

The code provided works with a specific html structure, which makes using "siblings" inappropriate as the images are not siblings in the tree:

<ul id="gallerySlideshow">
    <li>
        <a href="page9.html"><img src="thumbnails/thumb9.jpg" width="158" height="236" /></a>
        <ul id="noimg">
            <li>
                <a href=""><img src="Images/more-like-this.png" /></a>
            </li>
        </ul>
    </li>

    <li>
        <a href="page9.html"><img class="box2" src="thumbnails/thumb1.jpg" /></a>
        <ul id="noimg">
            <li>
                <a href=""><img src="Images/more-like-this.png" /></a>
            </li>
        </ul>
    </li>

    <li>
        <a href="page9.html"><img class="box" src="thumbnails/thumb3.jpg"  /></a>
        <ul id="noimg">
            <li>
                <a href=""><img src="Images/more-like-this.png" /></a>
            </li>
        </ul>
    </li>



    <li>
        <a href="page9.html"><img class="box1" src="thumbnails/thumb4.jpg" /></a>
        <ul id="noimg">
            <li>
                <a href=""><img src="Images/more-like-this.png" /></a>
            </li>
        </ul>
    </li>

    <li>
        <a href="page9.html"><img class="box3" src="thumbnails/thumb5.jpg" /></a>
        <ul id="noimg">
            <li>
                <a href=""><img src="Images/more-like-this.png" /></a>
            </li>
        </ul>
    </li>

    <li>
        <a href="page9.html"><img class="box4" src="thumbnails/thumb6.jpg" /></a>
        <ul id="noimg">
            <li>
                <a href=""><img src="Images/more-like-this.png" /></a>
            </li>
        </ul>
    </li>
</ul>

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

Tips on slowing down the Jquery UIBlock Plugin

Currently, I am implementing a plugin found at http://jquery.malsup.com/block/#overview. However, I am interested in configuring the blockUI feature to only be displayed if an AJAX request takes longer than 1 second. Otherwise, I would prefer for nothing ...

Send the user to the login page once their email has been verified

On my website, I have a process where users need to verify their email by clicking on a link sent through emails. When the user clicks on this verification link, I want them to be redirected to a page thanking them for confirming their account and then a ...

Update the content of a div and refresh it when a key on the keyboard is pressed

I need to hide the images in a div when I press a key on the keyboard. How can I achieve this? <div> <span role="checkbox" aria-checked="true" tabindex="0"> <img src="checked.gif" role="presentation" alt="" /> ...

Scrolling Container Following Down the Page, Halts at Its Own Bottom (Similar to Twitter)

I am facing an issue and need some help. I am working on creating a three-column page layout where the middle section is for posts, the right section is for links and references (a bit long), and the left section is fixed. My question is: How can I preven ...

Ajax is making a comeback to the world of text after straying towards

I'm encountering an issue with my code that is supposed to retrieve values from PHP using Jquery AJAX with JSON datatype. However, after the AJAX request is complete, it doesn't display properly in HTML and instead appears as text. Here is what ...

Ways to insert user data into a hidden input field

I am facing an issue with the input field on my website. Users can enter their desired input, and this data is copied into a hidden input field. However, the problem arises when new data replaces the old data. This is where I copy all the data: $('# ...

Array and setInterval are utilized to compute transitions accurately

I have been working on creating a dynamic element that gathers necessary information from data fields within the element. To achieve this, I utilized JavaScript to create arrays and iterate through them to retrieve the required data. Although I was success ...

Leveraging Greasemonkey along with jQuery to capture and manipulate JSON/AJAX data on a webpage

In my previous inquiry on Stack Overflow, I received some insight into my issue regarding Greasemonkey interpreting jQuery. However, the challenge remains in directing GM to retrieve data from a specific location and place it into an array. When visiting ...

Is there a way to retrieve the list element that was added after the HTML was generated?

How can I reference a list element added using the append function in jQuery within my onclick function? See my code snippet below: $(function() { let $movies = $('#showList') let $m = $('#show') $.ajax({ method: 'GET ...

Store data in Laravel's storage directory

I encountered an issue while trying to save files to the storage folder in Laravel after deploying the project on a web server (byethost7.com). The files were only being stored in the public folder. I ran the following command in the command prompt: >p ...

Mastering the Art of Leveraging Conditionals in JavaScript's Find Function

I'm curious about the implementation of an if statement in the JavaScript find function. My objective is to add the class "filtered-out" to the elements in my cars array when their values do not match. cars.map(car => active_filters.find(x => ...

Increase in JQuery .ajax timeout not effective

My website has a process where JavaScript sends a POST request to a PHP server using the .ajax() function. The PHP server then communicates with a third-party API to perform text analysis tasks. After submitting the job, the PHP server waits for a minute b ...

comparing caching with jquery deferred against promise

Currently, I have implemented code using jQuery Deferred and ajax to fetch data from a remote API, store it in localStorage, and retrieve it from there. However, this code has a bug where it doesn't display the data properly the first time it runs (re ...

Strangely Bizarre CSS Quirk

At this website, there seems to be an issue with how the footer displays on Internet Explorer and certain older versions of Firefox. However, it appears perfectly fine on Firefox 3.6.13. Any suggestions on what could be causing this discrepancy? ...

The navigation bar is showing my logo in a blurry and small format when viewed on a desktop

Currently, Twitter Bootstrap is being utilized on my website and a high-resolution logo has been successfully uploaded. The dimensions of the logo are 529 x 100 pixels, and here is the relevant CSS: .navbar-brand { float: left; padding: 12px 15p ...

Tips for implementing a sticky sidebar in HTML5 with jQuery

I currently have two files: index.php and aside.php. I've already created the contents of aside.php. Now, I want to make the aside page sticky. To achieve this, I referred to the following link: http://codepen.io/pouretrebelle/pen/yvcBz My struggle ...

Fetch HTML content from a local file using Vue

I am currently searching for a method to import HTML content from a file located at /src/activities/0/2/content.html The specific numbers in the path are interchangeable variables. My goal is to achieve something along the lines of mounted(){ this ...

Pattern to locate a CSS class identifier

I've been working on creating a regex to match valid CSS class name structures. Currently, my progress looks like this: $pattern = "([A-Za-z]*\.[A-Za-z]+\s*{)"; $regex = preg_match_all($pattern, $html, $matches); However, there are certai ...

Error encountered with select2 when using a remote JSONP dataset

When attempting to query the Geonames data using select2, everything seems to work fine with formatting the results. However, an error occurs once the results are populated, which I suspect is preventing the formatSelection function from running properly. ...

Ensure all asynchronous Ajax requests have completed before considering the page fully loaded

Many websites, such as YouTube, load the majority of their content after the DOM is ready using JavaScript. How can I ensure that all of these requests have been completed before injecting my code? window.onload = function() {}; The above code snippet do ...