JavaScript setInterval inside bind - javascript

I am trying to make an infinite periodic get loop:
<script type=text/javascript>
$(function() {
$('a#log').bind('click', setInterval(function() {
$.get(
$LOG + '/json_test',
{},
function(data) {
document.getElementById("logs").innerHTML = data.replace('\n', '<br/>');
}
);
}, 2000));
});
</script>
If I do this
<script type=text/javascript>
$(function() {
$('a#log').bind('click', function() {
$.get(
$LOG + '/json_test',
{},
function(data) {
document.getElementById("logs").innerHTML = data.replace('\n', '<br/>');
}
);
});
});
</script>
All works well, but without infinite loop.

As #sacho say, setInterval() returns a Number. You are binding that number as your click handler instead a function. That's why is not working, but...
You can do something like this is just want to call the ajax function every time is finished, you can't be sure that your response will be every 2000ms.
$('a#log').click(function (e) {
e.preventDefault();
infiniteLoop();
})
function infiniteLoop() {
$.get(
$LOG + '/json_test',
{},
function(data) {
$("#logs").html(data.replace('\n', '<br/>'));
infiniteLoop();
}
);
}
Note: Use jQuery (specially to manage the DOM) every time you can if you already loaded the library

You need wrap your setInterval function in a intermediate function to prevent it from executed before your click. In other word, a function inside a function.
$(function () {
$('a#log').bind('click', function () {
setInterval(function () {
$.get('example.json',{}, function (data) {
$('#logs').html(JSON.stringify(data).replace('\n', '</br>'));
});
}, 2000);
});
});
JSfiddle Working Demo: http://jsfiddle.net/x13sruaf/

$('a#log').on('click', infiniteLoop);
function infiniteLoop() {
setInterval(function() {
}, 2000);
}

You can try this :
<script type=text/javascript>
$(function() {
var refreshIntervalId;
$('a#log').bind('click', function (){
clearInterval(refreshIntervalId);
refreshIntervalId = setInterval(function() {
$.get(
$LOG + '/json_test',
{},
function(data) {
document.getElementById("logs").innerHTML = data.replace('\n', '<br/>');
}
);
}, 2000);
});
});
</script>

Related

How do i prevent my .done handler from being called multiple times?

I have this JQuery expression where i push a button, get some HTML from the server and then append it to a DOM node in my document:
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").click(function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data); //find better way of doing this
});
});
});
</script>
I have multiple ".addButton" buttons on my web site. The problem im experiencing is that after multiple clicks on the buttons my .done handler is being called multiple times.
My guess is that i have a list of event handlers that are being executed, I cant understand where / why this is done or how I prevent it from happening.
The problem is not taht you do the request is done more then once rathern then it calls done after its done.. you can keep the state in data object::
$(document).ready(function () {
var posting = false;
$(".addbutton").data("done", false).click(function () {
var addbuttonNode = $(this);
if (!addbuttonNode.data("done")) {
addbuttonNode.data("done", true);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data);
});
}
});
});
I would do the following:
$(".addbutton").click(function () {
var addbuttonNode = $(this);
addbuttonNode.attr('disabled',true);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data); //find better way of doing this
addbuttonNode.attr('disabled',false);
});
});
You could check it for any request pending:
$(document).ready(function () {
$(".addbutton").click(function () {
// if any request pending, return {undefined}
if ($.active) return;
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", {
id: '#guid'
}).done(function (data) {
// instead of .next().next()
$(addbuttonNode).nextAll('selector').first().append(data); //find better way of doing this
// or .parent().find('selector')
});
});
});
If you wish instead each button to be clickable only once, then use jQuery .one() method:
$(document).ready(function () {
$(".addbutton").one('click', function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", {
id: '#guid'
}).done(function (data) {
// instead of .next().next()
$(addbuttonNode).nextAll('selector').first().append(data); //find better way of doing this
// or .parent().find('selector')
});
});
});
Try to use bind, and unbind functions for the event handling. Then You can unbind the click function after it was executed once.
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").bind('click',function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' }).done(function (data) {
addbuttonNode.next().next().append(data);
});
addbuttonNode.unbind('click');
});
});
</script>
Another way of doing nearly the same, I think this should be better:
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").each(function(){
$(this).bind('click',function () {
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' }).done(function (data) {
addbuttonNode.next().next().append(data);
});
$(this).unbind('click');
});
});
});
</script>
I haven't tried it yet, but it should work, try it! :)
You can also set up a class or data attribute to check if the button was already clicked. You can then exit from the script like if($(this).hasClass('clicked')) { return; } or something...

Div not displaying correctly on show

<script type='text/javascript'>
$(document).ready(function () {
var fenster = $(location).attr('href');
if (fenster == 'http://www.cyrill-kuhlmann.de/index.php/') {
$('#intro-page').show(function () {
$(this).click(function () {
$(this).fadeOut(250);
});
});
}
});
</script>
I have a div that needs to be displayed in full-screen as an intro. The problem is that it doesn't display correctly; it just displays itself in the top left corner and grows until its full-screen. Why is it doing this?
show() takes the duration of the animation as a first parameter. You have given it a function, which is incorrect. Either you meant to chain your methods:
$('#intro-page').show().click(function () {
$(this).fadeOut(250);
});
Or, you did mean to put a callback function in there, but you missed out the first parameter; the duration:
$('#intro-page').show(250, function(){
$(this).click(function(){
$(this).fadeOut(250);
});
});
Documentation
show()
<script type='text/javascript'>
$(document).ready(function () {
var fenster = $(location).attr('href');
if (fenster == 'http://www.cyrill-kuhlmann.de/index.php/') {
$('#intro-page').show(function () {
$(this).click(function () {
$(this).fadeOut(250);
});
});
}
});
</script>
try the following:
<script type='text/javascript'>
$(document).ready(function () {
var fenster = $(location).attr('href');
if (fenster == 'http://www.cyrill-kuhlmann.de/index.php/') {
$('#intro-page').show();
$('#intro-page').click(function(){
// seperate it from show function call so you can have more access to object
// and do logic on it.
$(this).fadeOut(250);
});
}
});
</script>

Bind JQuery event to html created after pageload via jquery

I am developing a jquery module for add delete edit view etc.
My problem is when page load complete, a list of items populate. After selecting an item this item's subitems loaded via jquery and html built, appended. But on this table event not fired up. Jquery Live is no longer available. Instead "On" is not working.
I tried :
$(document).on('click', selector , function () { foo(); });
But when a button is clicked it triggers other buttons as well.
My code is below.
I have a working code except links on table which loaded by jquery.
var myModule = {
el: {
listbutton: $('#list-button'),
listcontainer: $('#list'),
detailbutton: $(".item-detail"),
deletebutton: $(".item-delete"),
editbutton: $(".item-edit")
},
init: function() {
...
myModule.el.listbutton.on("click",myModule.getMainData);
},
getMainData: function() {
...
success: function(data) {
myModule.BuildTable(data.Value.DataList);
}
...
},
BuildTable: function (hws) {
var c = "";
c += "<table>";
$.each(hws, function() {
c +=
'<tr>' +
'<td>' + this.Title + '</td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<tr>';
});
c += "</table>";
myModule.el.listcontainer.empty().append(c);
myModule.TableLinks();
},
itemDetails: function () {
alert("Detail clicked");
},
itemDelete: function () {
alert("Delete clicked");
},
itemEdit: function () {
alert("Edit clicked");
},
TableLinks: function () {
$(document).on('click', myModule.el.detailbutton, function () { myModule.itemDetails(); });
$(document).on('click', myModule.el.deletebutton, function () { myModule.itemDelete(); });
$(document).on('click', myModule.el.editbutton, function () { myModule.itemEdit(); });
},
};
myModule.init();
Can you try following:
TableLinks: function () {
$(document).on('click',
".item-detail",
function (ev) {
myModule.itemDetails();
ev.stopPropagation();
}
);
$(document).on('click',
".item-delete",
function (ev) {
myModule.itemDelete();
ev.stopPropagation();
});
$(document).on('click',
".item-edit",
function (ev) {
myModule.itemEdit();
ev.stopPropagation();
});
},
you need the delegation
$("selector on which item is added").on("click", "new item selector", function(){
});
ON and Delegate
You have to do something like this to use the "on" method.
$("table").on("click", myModule.el.detailbutton, myModule.itemDetails());
UPDATE: Just noticed, you have to used a selector not a jQuery object in the second parameter.
So $("table").on("click", ".item-detail", myModule.itemDetails());
your approach using on is exactly what you need, but should have been bit more careful on constructing the element object
el: {
listbutton: '#list-button',
listcontainer: '#list',
detailbutton: ".item-detail",
deletebutton: ".item-delete",
editbutton: ".item-edit"
},
and use it like this
init: function () {
$(myModule.el.listbutton).on("click", myModule.getMainData);
},
what you did is
TableLinks: function () {
$(document).on('click', myModule.el.detailbutton, function () { myModule.itemDetails(); });
...
},
which is similar to and which is wrong
TableLinks: function () {
$(document).on('click', $(".item-detail"), function () { myModule.itemDetails(); });
....
},
working fiddle

Ajax delay is not working

$(document).ready(function() {
setInterval($("#to").on("change keyup paste click mouseout", function() {
$.get('ajaxSearch.php', $("#form").serialize(), function(data) {
$('#result').html(data);
});
}, 3000);
});
ajax delay or setTimeout is not working. I want to delay on input field and run ajax after 3 sec but it is not working.
You should use setTimeout to delay the ajax request.
And if one of change keyup paste click mouseout event fired, you just cancel the previous delay and create a new one.
$(document).ready(function() {
var timer_id;
$("#to").on("change keyup paste click mouseout", function() {
if (timer_id) {
clearTimeout(timer_id);
}
timer_id = setTimeout(function() {
$.get('ajaxSearch.php', $("#form").serialize(), function(data) {
$('#result').html(data);
});
}, 3000);
});
});
Your syntax is wrong, also the setInterval() should be in the handler
$(document).ready(function () {
var interval;
$("#to").on("change keyup paste click mouseout", function () {
if (interval) {
return
};
setInterval(function () {
$.get('ajaxSearch.php', $("#form").serialize(), function (data) {
$('#result').html(data);
});
interval = undefined;
}, 3000);
});
});
Also if there is already a interval in progress, we need not have to add another call.
In your case you set deley to event handling ( and whyy you use setInterval but not setTimeout ? )
try
$(document).ready(function() {
$("#to").on("change keyup paste click mouseout", function() {
setTimeout(function(){
$.get('ajaxSearch.php', $("#form").serialize(), function(data) {
$('#result').html(data);
});
}, 3000);
});
});

JQuery Ajax + Dropdown Menu function only runs once

This function only runs once. How can I get it to run multiple times?
I have tried using live() as was suggested in another SO question, but that made no difference to the program.
$(function() {
$('#chooseTeam').live('change', (function() {
$.getJSON($SCRIPT_ROOT + '/_get_info', {
selectedDeck: $('#chooseTeam').val()
}, function(data) {
/* Do something */
});
}
return false;
}));
});
Did you tried with document ready instead of $function()
$(document).ready(function() {
$('#chooseTeam').live('change', (function() {
$.getJSON($SCRIPT_ROOT + '/_get_info', {
selectedDeck: $('#chooseTeam').val()
}, function(data) {
/* Do something */
});
}
return false;
}));
});
Regards

Categories

Resources