happycamper1221
happycamper1221

Reputation: 177

jQuery - Display image next to mouse cursor only when certain HTML attribute is met

I currently have an image displaying when the mouse hovers over a div... but i only what the image to display next to the mouse if a "div" has a HTML property of "align="center" and if it doesn't then i don't want the image to display?

I think i'm quiet close but i can't figure out how to call the var "divalign" attribute, spent all last night on it :S

$(document).ready(function() {
    var $img = $("#MainImage");
    $img.hide();
    var divalign = $("div").attr("align="center");
    $('div').mousemove(function(e) {
        $img.fadeIn(0);
        $img.offset({
            top: e.pageY - $img.outerHeight()-2,
            left: e.pageX - ($img.outerWidth()-18)
        });
    }).mouseleave(function() {
        $img.fadeOut(250);
    });
});

Thanks in advance.

Upvotes: 0

Views: 1524

Answers (4)

BuddhiP
BuddhiP

Reputation: 6451

It would be cleaner, if you could give these DIVs a class name (ex: class="alignCenter"), then register the event handler on those divs.

$('div.alignCenter').on('mousemove', function(e) {
     ..........................

});

Upvotes: 1

Dom
Dom

Reputation: 40491

Try this:

$('div[align="center"]').mousemove(function(e) {
        $img.fadeIn(0);
        $img.offset({
            top: e.pageY - $img.outerHeight()-2,
            left: e.pageX - ($img.outerWidth()-18)
        });
      }
    }).mouseleave(function() {
        $img.fadeOut(250);
    });

Upvotes: 0

coolguy
coolguy

Reputation: 7954

You have error in this line

 var divalign = $("div").attr("align="center");

Change that to

 var divalign = $("div").attr("align","center");

Upvotes: 1

BuddhiP
BuddhiP

Reputation: 6451

  $('div').mousemove(function(e) {
      if ($(this).attr('align') === 'center') {
        // only show if the align attribute has value center
        $img.fadeIn(0);
        $img.offset({
            top: e.pageY - $img.outerHeight()-2,
            left: e.pageX - ($img.outerWidth()-18)
        });
      }
    }).mouseleave(function() {
        $img.fadeOut(250);
    });

Upvotes: 4

Related Questions