开发者

mouseover action run just once (how to)

I would like to load data(via ajax) in a tooltip when the mouse is over a specific area. The problem is that the ajax call is made as long as my mouse is on that area. Is ther开发者_JS百科e any way, that I could make onmouseover (ajax call) efect happen just once? Here is the code:

$.post('calendar/event-details', {'eventId' :event.id},
            function (data){
                this.top = (ui.clientY + 15); this.left = (ui.clientX - 230);
                $('body').append( '<div id="vtip">' + data + '</div>' );
                $('div#vtip').css("top", this.top+"px").css("left", this.left+"px").fadeIn("slow");
                $('div#vtip').css("position","absolute");
                $('div#vtip').css("z-index", "+99");
            })


With .one:

$('element').one('mouseover', function() { /* ajax */ });

.one will detach the handler as soon as it is executed. As a result, it won't execute any more times.


You may want to hook your function to the onMouseEnter event instead of the onMouseOver event, along with a function hooked to the onMouseLeave event that hides the tooltip:

$('element').mouseenter(function() {
    /* Make request, show tooltip */
});
$('element').mouseleave(function() {
    /* Hide tooltip */
});

Note that the pure JS versions of these events are IE only, jQuery simulates the behaviour for other browsers


Use modern JS!

node.addEventListener("mouseover", function() {
    // Load data here
}, {once : true});

Documentation, CanIUse


I know it's been a long time since this has been a topic but for anyone looking for an easy alternative:

Set a static variable and check the last id used. If the last id is the current id, do nothing; quick example below

var LastId = null;

function Hover(Id){
    if(Id!= LastId){
        LastId = Id;
        $(Id).hide('fast');
    }else{
      //Do nothing; this will keep the function from recalling 
    }
}


I guess you need to use onmouseenter instead of onmouseover please read the docs here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜