painotpi
painotpi

Reputation: 6996

jQuery append() issue

I have 2 images one as a background image and 1 as a foreground image

the css is as follows :

#backImage{
    position: absolute;
    float: left;
    z-index: 0;
}

#mainImage{
    float: left;
    position: absolute;
    z-index: 1;
    left: 12px;
    top: 10px;
}

The mark-up is as follows :

<div id="homepageCarousel">
    <img id="backImage" src="discreet images/white_bg.png" />
        <img id="mainImage" src="discreet images/homepage_img1.jpg" />  
    //some other divs
</div>

I have a navigation bar at the top,

as I hover over each item in the bar, the mainImage should go and the image corresponding to the navigation item should appear.

How can I do this in jQuery, this is what I have thus far : (for now, I'm just trying to remove() and append() the mainImage)

$("#navigation li").mouseover(function(){
        $("#mainImage").remove();
    }).mouseout(function(){
        $("#backImage").append("<img id='mainImage' 
           src = 'discreet images/homepage_img1.jpg' />");
});

Upvotes: 0

Views: 144

Answers (3)

osahyoun
osahyoun

Reputation: 5231

A less expensive operation would be to just hide and show the main image:

var $main = $("#mainImage");

$("#navigation li").mouseover(function() {
  $main.hide();
}).mouseout(function() {
  $main.show();
});

Upvotes: 0

twilson
twilson

Reputation: 2062

You are removing #mainImage from the DOM I believe, so it can't come back. Would be better to change the $('#mainImage').style.display to either inline or none and vice-versa for the #backImage, and have them both loaded.

Removing them from the DOM each time is a little clumsy.

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

I'd suggest simply changing the src attribute of the img element, rather than appending and removing elements as those are expensive operations to run.

Upvotes: 1

Related Questions