DerickB
DerickB

Reputation: 119

Passing variables to .css to set top and left position

I know there are other questions regarding this but none of the solutions seem to work for me. I am unable to get my "top" and "left" positions to read the variables (YOff, XOff) defined above. It always defaults to 0,0. Any help would be appreciated. For what it's worth, I know the variables are calculating correctly because I alerted them to verify.

$(document).ready(function(){    
    $('.marker').mouseover(function(e){
        var location = $(this).attr("id");
        var offset_t = $(this).offset().top - $(window).scrollTop();
        var offset_l = $(this).offset().left - $(window).scrollLeft();

        var XOff = Math.round( (e.pageX - offset_l) );
        var YOff = Math.round( (e.pageY - offset_t) );

        $('.city').hide();
        $("#" + location + "-market")
        .show()
        .css({
            top: YOff, 
            left: XOff
        });

    });                
    $('.city').mouseleave(function(){
        $('.city').hide();
    }); 
});

A little detail on what I'm trying to do... On a map (bg image) when you mouseover a city (.marker) that has an absolute position I have a div (# + location + -market) show that contains some info on that city. I'd like to get that div to position close to the city.

Upvotes: 2

Views: 2204

Answers (2)

Amit Kumar
Amit Kumar

Reputation: 754

$("#selector").css({"top":YOff+ "px","left":XOff+ "px","position": "absolute" });

see in action with modified fiddle:- http://jsfiddle.net/md4cD/

Upvotes: 3

Blundering Philosopher
Blundering Philosopher

Reputation: 6805

Looking at -This Link- I changed your .css() function into this:

$("#" + location + "-market").show().offset({
    top: YOff, left: XOff
});

Which made your jquery file look like this:

$(document).ready(function(){ 
    $('.marker').mouseover(function (e) {
        var location = $(this).attr("id");
        var offset_t = $(this).offset().top - $(window).scrollTop();
        var offset_l = $(this).offset().left - $(window).scrollLeft();

        var XOff = Math.round((e.pageX - offset_l));
        var YOff = Math.round((e.pageY - offset_t));

        $('.city').hide();
        $("#" + location + "-market").show().offset({
            top: YOff, left: XOff
        });
    });

    $('.city').mouseleave(function () {
        $('.city').hide();
    });
});

Fiddle -Here-. Hopefully this produces the results you wanted!

Upvotes: 0

Related Questions