Davood
Davood

Reputation: 5645

how to stop mouseover function on my DIV to do not continue like a unlimited while loop?

I have a div and when click it ,it goes to fetch some information from server and put themes to itself content to show it to user it works fine but when it's work done and if user hold mouse on this div this start again to load data and this works continue like k unlimited loop how can i handle it when works done do not start to works again if user's hold mouse on it?

 <div id="picdiv" onmouseover="getit(this,'123')" onmouseout="killit(this)"></div>

my codes:

var xhr;

function getit(picdiv, pid) {

  $('#picdiv').html('please wait...');

 xhr= $.ajax({
    url: "/Getcontent",
    type: 'POST',
    dataType: 'json',
    data: null,
    contentType: 'application/json; charset=utf-8',
    success: function (content) {
        $('#picdiv').html(content);

    },
    error: function (content) {
       //do something
    }
   });
}

  function killit() {
  xhr.abort()
 }

Upvotes: 0

Views: 106

Answers (3)

coonooo
coonooo

Reputation: 205

use onmousein instead of onmouseover.

<div id="picdiv" onmousein="getit(this,'123')" onmouseout="killit(this)"></div>

Upvotes: 0

Praveen
Praveen

Reputation: 56509

Better bind your mouseover using .on('hover', function(e)

var xhr;
$('#picdiv').on('hover', function (e) {
    $(this).html('please wait...');
    $.ajax({
        url: "/Getcontent",
        type: 'POST',
        dataType: 'json',
        data: null,
        contentType: 'application/json; charset=utf-8',
        success: function (content) {
            $(this).html(content);

        },
        error: function (content) {
            //do something
        }
    });
}, function () {
    xhr.abort();
});

Upvotes: 2

Raver0124
Raver0124

Reputation: 522

You can simply put if condition in your code

    var xhr;
    var hasCompleted = false;

    function getit(picdiv, pid) {


if (!hasCompleted)
{
      $('#picdiv').html('please wait...');

     xhr= $.ajax({
        url: "/Getcontent",
        type: 'POST',
        dataType: 'json',
        data: null,
        contentType: 'application/json; charset=utf-8',
        success: function (content) {
            hasCompleted = true
            $('#picdiv').html(content);

        },
        error: function (content) {
           //do something
        }
       });
    }
}

  function killit() {
  xhr.abort()
 }

Upvotes: 2

Related Questions