Jquery Display Div with Interval - javascript

I am looking to hide several divs one by one or with a time interval of 5 seconds, i tried below doesn't seem to work though
<div id="container">
<div id="data1">123</div>
<div id="data2">456</div>
<div id="data3">789</div>
<div id="data4">012</div>
</div>
<script>
$('document').ready(function(){
window.setTimeout('mytimer()',5000);
});
$('document').ready(function(){
window.setTimeout('mytimer2()',10000);
});
$('document').ready(function(){
window.setTimeout('mytimer3()',15000);
});
$('document').ready(function(){
window.setTimeout('mytimer4()',20000);
});
function mytimer(){ $('#data1').hide(); }
function mytimer2(){ $('#data2').hide(); }
function mytimer3(){ $('#data3').hide(); }
function mytimer4(){ $('#data4').hide(); }
</script>

I would use single timeout function as your are hiding at regular intervals. There is one mistake in your code you need to pass the reference of function to setTimeout instead of passing the function call as a string.
Live Demo
window.setTimeout(mytimer,1000);
index = 1;
function mytimer()
{
$('#data' + (index++)).hide();
if(index <= 4) window.setTimeout(mytimer,1000);
}

You need to use $(document) instead of $('document')
$('document') will look for HTML Element with document tag, which doesn't exist.
Learn to use developer tools, Here's a good read: How to open the JavaScript console in different browsers?
Code
$(document).ready(function(){
window.setTimeout(mytimer,5000); //You can simply pass the function reference
window.setTimeout(mytimer2,10000);
window.setTimeout(mytimer3,15000);
window.setTimeout(mytimer4,20000);
});

Try it this way:
$(document).ready(function(){
window.setTimeout(mytimer, 5000);
window.setTimeout(mytimer2, 10000);
window.setTimeout(mytimer3, 15000);
window.setTimeout(mytimer4, 20000);
});
function mytimer(){
$('#data1').hide();
}
function mytimer2(){
$('#data2').hide();
}
function mytimer3(){
$('#data3').hide();
}
function mytimer4(){
$('#data4').hide();
}

Well you can use setInterval function too for this and once all the elements have been hidden you can clearInterval like one below:
DEMO HERE
function mytimer(elem){
console.log('came here');
$(elem).hide();
}
$(document).ready(function(){
var i=0;
var interval=null;
interval = window.setInterval(function(){
i++;
if(i<=$('#container').children().length)
mytimer("#data"+i);
else
{
clearInterval(interval);
return;
}
},5000);
});

Try this change and so on for the rest:
window.setTimeout(mytimer, 5000);// removed quotes and `()`
Another solution using jQuery fadeOut():
$(function() {
for (var i = 1; 4 >= i; i++)
$('#data' + i).fadeOut(5000 * i);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container">
<div id="data1">123</div>
<div id="data2">456</div>
<div id="data3">789</div>
<div id="data4">012</div>
</div>

Use .delay() in jquery . No Settimeout function needed.
$('#data1').delay(5000).hide('fast');
$('#data2').delay(10000).hide('fast');
$('#data3').delay(15000).hide('fast');
$('#data4').delay(20000).hide('fast');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div id="data1">123</div>
<div id="data2">456</div>
<div id="data3">789</div>
<div id="data4">012</div>
</div>

There are multiple errors in your code.
You have used $('document').ready(function(){}), which is incorrect. document is a keyword, it shouldn't be in quotes.
You don't have to use multiple instance of calling $(document).ready(). You can call all your statements from a single function. You can also use $(function(){}).
While calling the function name inside the timeout function, you shouldn't put them under quotes. They act like keywords after you have defined them in your code. The function call inside the Timeout function shouldn't be followed by (). So it should be window.setTimeout(mytimer,5000);
Please refer the fiddle : http://jsfiddle.net/65gs8s9y/
I have modified your code which works fine now:
$(document).ready(function(){
window.setTimeout(mytimer,5000);
window.setTimeout(mytimer2,10000);
window.setTimeout(mytimer3,15000);
window.setTimeout(mytimer4,20000);
});
function mytimer(){
$('#data1').hide();
}
function mytimer2(){
$('#data2').hide();
}
function mytimer3(){
$('#data3').hide();
}
function mytimer4(){
$('#data4').hide();
}

Related

dynamically change assigned click function

<div id='example' data-fn='functiona'>OK</div>
$('#button').click function(){
$('#example').attr('data-fn', functionb');
});
function functiona(){
console.log('functiona');
}
function functionb(){
console.log('functionb');
}
$('#example').click(function(){
// execute function currently stored inside data-fn attribute
});
Probably everything is clear.
I need dinamically change the function which will be executed by clicking on example.
The current function should be stored inside data-fn.
Any help?
What you want to do is described in Can you set a javascript function name as an html attribute?
But I suggest that you solve it that way:
$('#button').click(function() {
$('#example').off('click.myNamespace') // remove the previously assigned callback
.on('click.myNamespace', creatClickCallback(functionb)); // register the new callback
});
function functiona() {
console.log('functiona');
}
function functionb() {
console.log('functionb');
}
function creatClickCallback(functionToCall) {
return function(evt) {
functionToCall()
}
}
$('#example').on('click.myNamespace', creatClickCallback(functiona));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='example'>OK</div>
<div id='button'>button</div>
This way you ensure that you do not accitantily name a function the wrong way, because you pass it as an actual reference to that function instead of a string.
Couldn't you just store the function name, then when you click you check which function is then call it and update the function to which one you want?
Something like this:
function functiona(){
console.log('called functiona');
document.body.style.background = '#aaa';
}
function functionb(){
console.log('called functionb');
document.body.style.background = '#fff';
}
$('#example').on("click", function(ev){
var func = $(ev.target).attr('data-fn');
console.log(func);
window[func]();
});
$('#changer').on("click", function(ev){
//HERE you can change the function will be called based on what you want
//Here I just changed it with a simple if...
var fn = $("#example").attr("data-fn");
if (fn == 'functiona'){
$("#example").attr("data-fn", "functionb");
}else {
$("#example").attr("data-fn", "functiona");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='example' data-fn='functiona'>Click Me to call function</div>
<button id='changer'>Change Function</button>
Here, the global variable window have your functions stored, so going through it by it's name and calling it, should work, if this name exist as a function window[stringOfFuncionName]();
This is not the best way of doing what you need (actually you didn't let completely clear your final objective), but this maybe can help.

Call single function for multiple classes

I have two buttons: one with class btn-star, and the other with btn-current. I am calling an independent function on each of their clicks. But now, I want to call only one function when they are called.
My code is similar to this:
$('document').ready(() => {
$(document).on('click', '.btn-star', function () {
// Do stuff
}
$(document).on('click', '.btn-current', function () {
// Do stuff
}
}
You can try this code. You can use multiple elements click event for one action with only one line code, Just use a comma for separating elements
$('document').ready(() => {
const myFunction= () => {
// Your Code here...
}
$(document).on('click', '.btn-current, .btn-current', function () {
myFunction();
}
}
You can define a function separately and pass it in as callback for both buttons' on click handler. For example -
$('document').ready(() => {
const commonFunc = () => {
// do common stuffs here
}
$(document).on('click', '.btn-star', commonFunc());
$(document).on('click', '.btn-current', commonFunc());
}
Hope that helps!
If you want to call the same function you can select your two button classes, using a simple j-query expression:
$('.btn-star, .btn-current').click(function() {
// Do stuff
}
Ad your selectors separated by a comma, inside the quotation marks.
You can read more about j-query selector at this link:
https://www.sitepoint.com/comprehensive-jquery-selectors/
A little shorter code...
$('document').ready(() => {
function commonFunc() {
//do stuffs here
}
$('.btn-star, .btn-current').on('click', commonFunc);
}
you can try like this:
function test()
{
//your code
}
$(".btn1, .btn2").on("click", funciton(){
test();
});
Try below code
$('.btn-star, .btn-current').on('click', function () {
// Do shared stuff
});
Reference: http://api.jquery.com/on/
Why is [Javascript] tagged on this post? If it is meant to be there, I'm assuming you are going to accept javascript responses right?
If you're going javascript, it is much easier, and you can just add a onClick='function()' to your html code and do your functions in there.
<html>
<head>
<script>
function buttonFunction(buttonName){
//EDIT 3.0: You can make one button do the same as the other button, but you can also make it do something else at the same time!
if(buttonName == 'btn-star'){
//other code such as:
alert("Stars are awesome!");
}
alert("You just clicked " + buttonName);
}
</script>
</head>
<body>
<div id='button1'>
<button id='btn-star' onclick='buttonFunction("btn-star")'>btn-star</button>
</div>
<br/>
<div id='button2'>
<button id='btc-current' onclick='buttonFunction("btn-current")'>btn-current</button>
</div>
</body>
</html>
If you want, you can also additionally make one button do the same as the other, and then after that do something different like I did in this snippet.
P.S: I'm just assuming javascript is allowed, because after all, it is tagged on this post.
EDIT: I showed you an example of one button doing slightly differently then the other, but still the same in a way
ANOTHER EDIT: You can do a lot of stuff with this, added ideas on what else you could do with this snippet.
You can try
$('.btn-star , .btn-current').on('click', function () {
//do something common for elements
});

Hiding an element using jQuery

I'm trying to hide an element using jQuery, but I think I did something wrong. Please take a look at my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
$(function(){
function hide(id) {
$("#"+id).hide();
}
});
hide("test");
</script>
<div id = "test"> Hello </div>
Sushil is right, but also, your "hide" function should be outside the $() function and the call to it goes on the inside. The whole thing looks like this:
function hide(id) {
$("#" + id).hide();
}
$(function(){
hide("test");
});
Putting the hide() function inside of the $() makes it so you can only call it from inside of the $(). So, put it on the outside, and then you can call it from anywhere, including, from inside the $() part.
your javascript code should be like
$(function() {
function hide(id) {
$("#" + id).hide(); // notice the '+'
}
});

Using a plugin on dynamically generated HTML

I'm generating some HTML at runtime and I'm wondering how to make a plugin work on the newly created HTML. I've got something that looks llike this:
<input type="text" class="SomeClass">
<div id="Test"></div>
<script>
function Start() {
setTimeout(function () {
$('#Test').html('<input type="text" class="SomeClass">');
}, 1000);
}
$(".SomeClass").SomePlugin();
$(Start);
</script>
The input element has all the functionalities of the plugin but when I add the HTML inside the Test div the input element inside there doesn't work as expected. How can I use the plugin on dynamically generated HTML?
For plugin to work with new created elements, you need to init the plugin on those elements for it to work. There are several ways to do this, such as calling it again when new elements are added.
If you just want to avoid changing your code and adding that, you could override jquery html to check if you are adding an element with SomeClass and call the plugin for it automatically:
(function($)
{
var oldhtml = $.fn.html; //store old function
$.fn.html = function() //override html function
{
var ret = oldhtml.apply(this, arguments); // apply jquery html
if(arguments.length){
if(ret.find(".SomeClass").length){
ret.find(".SomeClass").SomePlugin(); // call plugin if the html included an element with .SomeClass
}
}
return ret;
};
})(jQuery);
$.fn.SomePlugin = function() {
$("body").append("plugin activated <br/>");
}
function Start() {
setTimeout(function() {
$('#Test').html('<input type="text" class="SomeClass">');
$('#Test').html()
}, 1000);
}
$(".SomeClass").SomePlugin();
$(Start);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="SomeClass">
<div id="Test"></div>
I opted for a solution that used jQuery promises. Here is the Fiddle
The HTML (basic copy of yours):
<input type="text" class="SomeClass">
<div id="Test"></div>
The Javascript:
$.fn.SomePlugin = function(){
$(this).val("plugin activated");
}
function Start() {
alert('hi from start');
$('#Test').html('<input type="text" class="SomeClass">');
return $.when();
}
$(document).ready(function(){
Start().then(function () {
alert('hi from done');
$(".SomeClass").SomePlugin();
});
});
I had some issue with the $(Start) so i opted for the document.ready approach. The only real difference is that Start returns $.when (SO Post Here) and I chain a 'then' after the call to start. This allows the page to setup and then you can run any plugins that you want and ensure that the required elements are in the DOM before the plugin attempts to manipulate them.

Call JavaScript function in a jQuery chain

function jsFunc() {
alert('i am js!');
}
$('#node').slideDown().call(jsFunc());
Of course, the function isn't called 'call'.
** EDIT **
(Added solution on behalf of the OP).
Solution
http://jsfiddle.net/gx2mJ/1/
or
HTML:
<div id="content">
<p class="article">
this is an article
</p>
</div>
JavaScript:
function callBack() {
$("#content .article").html("the callback has been called");
}
$(document).ready(function() {
$("#content .article").slideUp(0);
$("#content .article").each(function(i) {
$(this).delay(i*250).slideDown(function(){
//if ($("#content .article:animated").length < 1) {
callBack();
//}
});
});
});
You can't do that by default, but you could easily add it as a plugin:
$.fn.call = function (fn, args, thisp) {
fn.apply(thisp || this, args);
return this; // if you want to maintain chainability -- other wise, you can move the return up one line..
}
Though I'm not sure why you would want to do that. If you're thinking it won't be run until after the slide is done, then you'd be wrong because jQuery animations are asynchronous.
why not just use a callback function? almost all jquery functions have them.
$('#node').slidedown('normal', function(){jsFunc()})
$("#content article").each(function(i) {
$(this).delay(i*250).slideDown();
}).callBack();
The whole reason for having the callback in the chain is so it will run AFTER all the animations have taken place.
try this instead,
$("#content .article").each(function(i) {
$(this).delay(i*250).slideDown(function(){
if ($("#content .article:animated").length < 1) {
callBack();
}
});
});
the same problem
What is your objective of calling the jsFunc()?
If you want it as a callback you can use the sysntax given here
ex:
$('#node').slidedown('normal', function(){jsFunc()}).
But if you want the function jsFunc to be able to call as a plugin, you need to write a plugin as suggested by CD Sanchez.
I think again there is one issue in your sample code, you are calling the function jsFunc and passing the value returned by jsFunc as an argument to the call function. If you want to pass the function jsFunc as the callback function you need to use the syntax
$('#node').slideDown().call(jsFunc);
(Added solution on behalf of the OP).
Solution
http://jsfiddle.net/gx2mJ/1/
or
HTML:
<div id="content">
<p class="article">
this is an article
</p>
</div>
JavaScript:
function callBack() {
$("#content .article").html("the callback has been called");
}
$(document).ready(function() {
$("#content .article").slideUp(0);
$("#content .article").each(function(i) {
$(this).delay(i*250).slideDown(function(){
//if ($("#content .article:animated").length < 1) {
callBack();
//}
});
});
});
$("#content article").each(function(i) {
$(this).delay(i*250).slideDown();
}).callBack();
The whole reason for having the callback in the chain is so it will run AFTER all the animation triggers have taken place.

Categories

Resources