Question

Here is the code I have written. What it does is when hovering over the first item it adds a class, and that class has a background image, and also adds html to explain about the image that shows up from the hover. The issue happens after I hover over the next item, which takes place of the old info that showed up from the previous hover with a new addclass image, and new html explaining the new image that shows up. So after if I go back to the first item, it wont replace the image. I am sure I need a removeClass somehow, but I would like it to tell it to remove class if there is something in place. Here is the code:

  function imageInfo(){
    $('#item_one').hover(function(){
        $('#img_holder').addClass('img_one');
        $('#about_me_cont aside p').html('text explaining img 1');
    });
    $('#item_three').hover(function(){
        $('#img_holder').addClass('img_two');
        $('#about_me_cont aside p').html('text explaining img 2');
    });
    $('#item_three').hover(function(){
        $('#img_holder').addClass('img_three');
        $('#about_me_cont aside p').html('text explaining img 3');
    });
  }

This is the CSS:

.img_one{
    background-image: url('../images/img1.jpg');
    background-repeat: no-repeat;
    background-size:contain;
}
.img_two{
        background-image: url('../images/img2.jpg');
        background-repeat: no-repeat;
        background-size:contain;
}
.img_three{
    background-image: url('../images/img3.jpg');
    background-repeat: no-repeat;
    background-size:contain;
}

there is a paragraph which the html gets injected into and I style it in CSS. So what happens after I hover over item one and then go to item 2 and then back to item 1, it keeps item 2 image there, the html changes, but the image from item 2 does not. How would I write for it to removeClass if there is a class there so it will go back to displaying the first item image again? Thanks for you help!

Was it helpful?

Solution

You've got a typo in your code: where it should be

$('#item_two').hover(function(){

it says item_three instead.

That said, there's nothing wrong with using the jQuery removeClass function even if there's no classes, it won't fail. So you can do:

function imageInfo(){
    $('#item_one').hover(function(){
        $('#img_holder').removeClass().addClass('img_one');
        $('#about_me_cont aside p').html('text explaining img 1');
    });
    $('#item_three').hover(function(){
        $('#img_holder').removeClass().addClass('img_two');
        $('#about_me_cont aside p').html('text explaining img 2');
    });
    $('#item_three').hover(function(){
        $('#img_holder').removeClass().addClass('img_three');
        $('#about_me_cont aside p').html('text explaining img 3');
    });
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top