running a jquery task forever - javascript

I am new in jQuery / java script; trying to make a slider. Please help with the following problem.
I want to make a div (class is slider) fade-out and fade-in forever; please check this code.
Is it possible to use setInterval() function for this?
<html>
<head>
<title>Slider</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../jquery/jquery.min.js"></script>
<style>
.slider1{
width: 500px;
height: 250px;
margin: 0 auto;
background-image: url(images/rectblue.png);
}
</style>
<script type="text/javascript">
var runForever = $(document).ready(function () {
$(".slider1").fadeOut(2000, function () {
$(".slider1").fadeIn(2000);
});
});
runForever();
//setInterval(runForever, 4000);
//This runs the function 'runForever' one time only, how to run it every 4 sec?
//the above commented out code does not work.
</script>
</head>
<body>
<div class="slider1"></div>
</body>

You didn't define runforever as a function, you made it the result of the call to $(document).ready. If you define it as a function and put it in a setInterval, it works.
var flashSlider = function () {
$(".slider1").fadeOut(2000, function () {
$(".slider1").fadeIn(2000);
});
};
$(document).ready(function () {
setInterval(flashSlider, 4000);
});
Fiddle: http://jsfiddle.net/uoqdfhdb/
I think it's a little more jQuery-elegant to write the flash-forever recursively:
var flashForever = function () {
$(".slider1").fadeOut(2000).fadeIn(2000, flashForever);
};
$(document).ready(function () {
flashForever();
});
http://jsfiddle.net/uoqdfhdb/1/
Except I wonder if the tail-recursion will eventually cause stack overflow.

This should work:
var $slider = $('.slider1');
var flashSlider = function () {
$slider.fadeToggle(2000, flashSlider);
};
$(document).ready(function () {
flashSlider();
});

Yes it is possible. You should put all of your code in $(document).ready argument for the callback function, you can't capture that as a function. It is a listener on the document object to make sure everything is loaded. So it should look something like:
$(document).ready(function () {
var runForever= function()
{
$(".slider1").fadeOut(2000, function () {
$(".slider1").fadeIn(2000);
});
}
setInterval(runForever, 4000);
//This runs the function 'runForever' one time only, how to run it every 4 sec?
//the above commented out code does not work.
});

Just let me rewrite your code:
$(document).ready(function() {
var runForever = function() {
$(".slider1").fadeOut(2000, function() {
$(".slider1").fadeIn(2000);
});
}
runForever();
setInterval(function(){runForever();}, 4000);
});
Here is a live preview
you could also write a recursive function calling itself again and again after completing animation:
$(document).ready(function() {
var runForever = function() {
$(".slider1").fadeOut(2000, function() {
$(".slider1").fadeIn(2000, function(){
runForever();
});
});
}
runForever();
});

$(document).ready(function () {
var $slider1 = $(".slider1");
function runForever(){
$slider1.fadeOut(2000, function () {
$slider1.fadeIn(2000);
});
clearTimeout(t);
var t = setTimeout(runForever, 4000);
}
runForever();
});

Related

Conflict in using multiple JQUERY libraries

In my web application, I have a datepicker jquery, Everything works well, until I added a new jquery codes referencing a diffrent library. This Jquery's purpose is to fixate a gridview header.
After I added this code, the datepicker stopped working. What could be causing the conflict?
Here are the codes
1. DatePicker JQuery locatred in external JS File
$(function () {
$("#txtdatefrom").datepicker();
});
$(function () {
$("#txtdateto").datepicker();
});
window.onload = function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}
function endRequestHandler(sender, args) {
init();
}
function init() {
$(function () {
$("#txtdatefrom").datepicker();
});
$(function () {
$("#txtdateto").datepicker();
});
}
$(function () { // DOM ready
init();
});
3. Jquery to fix gridview header.
After adding this the the datepicker feature stopped working.
<script type = "text/javascript">
//not needed kasi it produced double scrolls, pero pwede din e.. ewan
$(document).ready(function () {
$('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
window.onload = function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}
function endRequestHandler(sender, args) {
init();
}
function init() {
$(document).ready(function () {
$('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
}
$(function () { // DOM ready
init();
});
</script>
upon checking the browser console to locate the error, here is the reason:
jquery-ui-1.8.19.custom.min.js:5 Uncaught TypeError: Cannot read property 'ui' of undefined
The issue is due to conflict in definition of init() function. In both the files, you have used the same name. Try renaming one of them and your issue should be fixed.
Edit: Try changing the second snippet to the following:
<script type = "text/javascript">
//not needed kasi it produced double scrolls, pero pwede din e.. ewan
$(document).ready(function () {
$('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
window.onload = function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}
function endRequestHandler(sender, args) {
fixGridHeader();
}
function fixGridHeader() {
$(document).ready(function () {
$('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
}
$(function () { // DOM ready
fixGridHeader();
});
</script>
I already found the answer. Based on research, using multiple Jquery codes or libraries can be done by using jquery.noConflict() code.
javascript for Datepicker
var $152 = jQuery.noConflict();
$152(function () {
$152("#txtdatefrom").datepicker({
changeMonth: true,
changeYear: true
});
//On UpdatePanel Refresh
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm.add_endRequest(function (sender, e) {
if (sender._postBackSettings.panelsToUpdate != null) {
$152(function () {
$152("#txtdatefrom").datepicker({
changeMonth: true,
changeYear: true
});
});
}
});
};
for gridview header
var $151 = jQuery.noConflict();
//not needed kasi it produced double scrolls, pero pwede din e.. ewan
$151(document).ready(function () {
$151('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
window.onload = function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}
function endRequestHandler(sender, args) {
init();
//fixGridHeader();
}
function init() {
//function fixGridHeader()
$151(document).ready(function () {
$151('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
}
$151(function () { // DOM ready
//fixGridHeader()
init()
});
just create a variable that will be assigned with a jquery.noconflict() function. then replace all $ with the created variable per javascript. then it will work already.
reference: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

JavaScript setInterval inside bind

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>

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>

How do I make a div hide onclick and make it show when it's clicked again?

I have this code:
<script>
(function ($) {
$(document).ready(function () {
$("#thisclick, #thisclick2").click(function () {
if ($('.example').is(":hidden")) {
$(this).html($(this).html().replace(/Hide/, 'Show'));
} else {
$(this).html($(this).html().replace(/Show/, 'Hide'));
}
// Do it afterwards as the operation is async
$(".example").hide();
});
});
})(jQuery);
</script>
The way the current code works is that if #thisclick is clicked it hides #example. Which is what I require but when #thisclick is clicked again i want it to show #example. Using the above code, it won't work. What must I do to achieve this?
You should be able to change your code to as follows to get it to work:
(function ($) {
$(document).ready(function() {
$("#thisclick").click(function () {
$("#example").slideToggle("slow");
});
});
})(jQuery);
Here is a link to a quick sample:
http://jsfiddle.net/andyjmeyers/szmXp/
Are you expecting like
<button>This click</button>
<p style="display: none">Example</p>
<script>
$("button").click(function () {
$("p").toggle();
});
</script>
Please check it on http://jsfiddle.net/X5r8r/1107/
<script>
(function ($) {
$(document).ready(function() {
$("#thisclick").click(function () {
if ($('#example').is(":hidden")) {
$(this).html($(this).html().replace(/Hide/, 'Show'));
} else {
$(this).html($(this).html().replace(/Show/, 'Hide'));
}
// Do it afterwards as the operation is async
$("#thisclick").slideToggle("slow");
if($("#example").attr("isHidden") == "1")
$("#example").slideToggle("slow");
$("#example").attr("isHidden","1");
});
});
})(jQuery);
</script>
You can do this:
$("#thisclick").click(function () {
if ($('#example').hasClass("hidden"))
{
$('#example').removeClass("hidden");
$('#example').show();
}
else
{
$('#example').addClass("hidden");
}
}
or more easily:
$("#thisclick").click(function () {
$('#example').toggleClass("hidden");
}
define style":
.hidden
{ display:none;}

Mouse in-out events for Javascript

question from a beginner..
I want to show/hide an inner div when the mouse enter/out from the parent div. I tried first with onmouseover, onmouseout events, but the problem is that onmouseover keep firing while the mouse over the div, and I want it to fire one time only.
I found JQuery events that might help me, but I don't know where can I put this code because my divs exist in a template for a control, and there is no onload event for the div.
<script type="text/javascript" language="javascript">
// Where should I call this !!!
function Init(sender) {
$(sender).bind("mouseenter", function () {
$(sender.childNodes[1], this).show(500);
}).bind("mouseleave", function () {
$(sender.childNodes[1], this).hide(500);
});
}
</script>
Any help!
You can use mouseenter and mouseleave events.
You can put your code in the and bind your with these events.
<script type="text/javascript" language="javascript">
$(document).ready(function(){
Init('.your_div_class');
});
function Init(sender) {
$(sender).bind("mouseenter", function () {
$(sender.childNodes[1], this).show(500);
}).bind("mouseleave", function () {
$(sender.childNodes[1], this).hide(500);
});
}
</script>
Thanks for everybody. as YNhat said, I have to use classes instead of Ids. and this is the code that I used and it's work well.
$(document).ready(function () {
InitEntities();
});
function InitEntities() {
var parentDiv = $(".parentDivClass");
parentDiv.each(function (index) {
var childDiv = $(this).children(".childDivClass");
$(this).bind("mouseenter", function () {
$(childDiv, this).show(250);
}).bind("mouseleave", function () {
$(childDiv, this).hide(250);
});
});
}
css
.parent_div .inner_div
{
display:none;
}
.parent_div:hover .inner_div
{
display:block;
}
This is what I use in a script.
Once the document is fully loaded ($(document).ready) the mouseover event is bound.
I then unbind the event when I'm in it (to prevent it from spamming the event) and bind the mouseleave event.
$(document).ready(function() {
$("#loginformwrapper").bind("mouseover", showLoginForm);
});
function showLoginForm() {
$("#loginformwrapper").unbind("mouseover", showLoginForm);
$("#loginform").animate({
top: '+=80'
}, 1000, function() {
$("#loginform").bind("mouseleave", hideLoginForm);
});
}
function hideLoginForm() {
$("#loginform").unbind("mouseleave", hideLoginForm);
$("#loginform").animate({
top: '-=80'
}, 1000, function() {
$("#loginformwrapper").bind("mouseover", showLoginForm);
});
}
Use this:
<script type="text/javascript">
$(function(){
var mydiv = $("#parent_div_id");
$(mydiv).bind("mouseenter", function () {
$(mydiv.childNodes[1], this).show(500);
}).bind("mouseleave", function () {
$(mydiv.childNodes[1], this).hide(500);
});
});
</script>
replace the "parent_div_id" with the id of your parent div

Categories

Resources