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

What is the best way to consistently update the name of a variable in PHP?

Forgive me in advance if my question seems a bit confusing. I currently have three separate PHP files. The first one prompts the user to select the quantity of products they want (between 1-20) using a variable called $quantity. Once a number is chosen fr ...

Concealing overflow for text content through CSS styling

I am currently working with an element that contains both an image and text. View the Fiddle here Note: To see the full grid, resize the preview accordingly. The CSS I have written is as follows: .gridster .gs-w .item{ position: relative; wi ...

Exploring the distinction between absolute elements nested within other absolute elements and relative elements nested within absolute elements

My latest CSS experiment involved creating a flag of a country. Check out my code: div.flag { width: 900px; height: 600px; background-color: red; position: relative; } div.flag > div { position: absolut ...

What is the best way to set the width of an iframe within a <td> element to be 33% of the screen?

I am facing an issue with scaling an iframe dynamically inside a <td> element. My goal is to make the iframe occupy 33% of the screen width while automatically adjusting its height. Here is what I have tried: <iframe src="google drive presentati ...

Transitioning the CSS background for a lightbox display

I am currently experimenting with creating an image that fades in along with its background when clicked using the :target selector. (Similar to Lightbox: , but done purely with CSS). Here is the HTML: <a href="#firstimg"><img src="img/thumb-3.j ...

What sets apart the two syntaxes for JavaScript closures?

Similar Query: Is there a distinction between (function() {…}()); and (function() {…})();? I've come across a way to prevent variables from becoming global by using the following syntax: (function ($, undefined) { })(jQuery); Rec ...

Is there a way to showcase an epub format book using only HTML5, CSS, and jQuery?

Can ePub format books be displayed in a web browser using only HTML5, CSS, and jQuery? I would appreciate any suggestions on how to accomplish this. Additionally, it needs to be responsive so that it can work on iPad. While I am aware of this requirement, ...

Upon clicking, the input texts revert to their original default values

I have a form below that is working as intended, except for one issue. When I click the 'Add' link, the texts in all the textboxes revert to their default values, as shown in the images. How can I resolve this problem? Thank you. before click: ...

Why is it that when I refresh the page in Angular, my logged-in user is not being recognized? What could be causing this

I am developing a Single Page Application using the combination of Angular JS and Node JS. In my HTML file, I have defined two divs and based on certain conditions, I want to display one of them using ng-if. However, I noticed that the model value used in ...

Creating a conditional statement in jQuery that will append text to a specific DIV element after a form has been successfully

I currently have a form set up that is functioning properly, but I am looking to make some changes. Instead of redirecting the user to a new page with a success message upon submitting the form, I want the success message to be displayed in a div next to t ...

The WordPress website encounters a jQuery Ajax call failure without any response

I'm currently developing a custom WordPress plugin and encountering an issue with one specific jQuery Ajax call within the code. The call is located inside an 'onbeforeunload' function, but I don't think that's causing the problem. ...

A method for automatically refreshing a webpage once it switches between specific resolutions

On my page www.redpeppermedia.in/tc24_beta/, it functions well at a resolution of over 980px. However, when the resolution is brought down to 768px, the CSS and media queries alter the layout. But upon refreshing the page at 768px, everything corrects itse ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

Please indicate the number of lines for the href within the span element

I'm struggling with formatting a <span> tag, specifically the .lastMessageLink class that contains an <a> element with the .lastMessageText class. The content within .lastMessageText can vary from just a few characters to a lengthy paragra ...

JavaFX Animation for Charting

My FXML file contains a JavaFX AreaChart <AreaChart id="myAreaChart" onMouseClicked="#handleAreaChartMouseClicked" GridPane.columnIndex="0" GridPane.rowIndex="0" fx:id="myAreaChart" > <xAxis> <Nu ...

Issue encountered with jQuery nested hover events and the removeClass() function being triggered on mouseleave

I have a nested list structure that I am working with: <ul class="menu-wrapper"> <li> <a href="#">Menu item</a> <ul class="sub-menu"> <li> < ...

Utilize AJAX and jQuery to seamlessly upload files through the PHP API

I have code in the following format. PHP file : <form action="http://clientwebapi.com/createEvent" id="form_createEvent" method="post" enctype="multipart/form-data"> <input type="text" name="image_title" /> <input type="file" name="media" ...

As a Java developer, I am currently facing challenges with mastering jQuery

Hi everyone, I am completely new to jQuery and have just started using the auto complete feature. I would like to make it so that when I click on an item provided by the auto complete, the page automatically submits to another page. Here is the code I a ...

When a PHP if statement is triggered by reading a text file, it activates a checked

I am working on a PHP project that involves an on-off button and a txt file. The goal is to have the button disabled (with 'unchecked' echoed) when the value in the txt file is true, and enabled (with 'checked' echoed) when the value is ...

Discovering similarities among array elements by looping through an array

Two sets of arrays have values obtained using the data-attribute(data-product-name). One set contains the full list of available items, while the other set consists of selected items associated with a country. <!-- the item list --> <div ...