JQuery Click() function executes only once - javascript

In the following code, CLICK() method runs only one time:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.10.2.min.js"></script>
<script>
$(function(){
var arr = ["test1", "test2", "test3"];
var i=0;
$("#btn").click( function () {
while(arr[i])
alert(arr[i++]);
});
});
</script>
</head>
<body>
<div id="btn">Click Me</div>
</body>
</html>
Whats the problem?
I read all the other subjects but didn't help.

It does: - Just reset your i to 0. In your handler the condition fails second time because your i becomes array.length from your previous execution and it fails, since there is no item at arr[array.length] i.e3 in your case.
$("#btn").click(function () {
while(arr[i])
alert(arr[i++]);
i = 0; //here reset it
});
or just move it to the scope of the function.
$("#btn").click(function () {
var i = 0;
while(arr[i])
alert(arr[i++]);
});

The click method runs on every click, but after the first one it doesn't enter while loop anymore, because i === 3.

try this:
$("#btn").on('click', function () {
while(arr[i])
alert(arr[i++]);
});

I think the problem is caused by variable i, please move i to click function, such as:
$("#btn").bind('click', function(){
var i = 0;
while(arr[i])
alert(arr[i++]);
});

Related

Jquery Display Div with Interval

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();
}

JavaScript function problems

I can't get this to display an alert fed as a function argument. I have compared to examples and can't see the problem causing it not to work. I have included my html and JavaScript below, any help in where I'm going wrong will be very gratefully received. Thanks A
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="testjs.js"></script>
</head>
<body>
<div id = "testbed">
<a id = "testlink" href = "#number1">Test click</a>
</div>
</body>
</html>
JavaScript:
$(document).ready(function() {
$.fn.newmodalcontrols = function(modelspec) {
alert(modelspec);
} // end newmodalcontrols
$('#testlink').click(function() {
$(this).parent().newmodelcontrols('number1');
}); // end testlink click function
}); // end ready
You just have a typo. Change newmodelcontrols to newmodalcontrols.
JavaScript
$(document).ready(function () {
$.fn.newmodalcontrols = function (modelspec) {
alert(modelspec);
}
$('#testlink').click(function () {
$(this).parent().newmodalcontrols('number1');
});
});
Update: added a jsfiddle example.
You have a typo: newmodalcontrols and newmodelcontrols are not equivalent (note the a/e): corrected the typo, in a JS Fiddle demo:
$(document).ready(function () {
$.fn.newmodalcontrols = function (modelspec) {
alert(modelspec);
} // end newmodalcontrols
// ^- Should be an 'e'
$('#testlink').click(function () {
$(this).parent().newmodelcontrols('number1');
// ^- Or this should be an 'a'
}); // end testlink click function
}); // end ready
Incidentally, in Chromium, this would have been shown in the Web Inspector's JavaScript console as:
Uncaught TypeError: Object [object Object] has no method 'newmodelcontrols'
Which should have drawn your attention to the name of the method you were using/defining.
You got a typo.
Check out fiddle
http://jsfiddle.net/AUEZJ/
$(document).ready(function () {
$.fn.newmodelcontrols = function (modelspec) {
alert(modelspec);
}; // end newmodalcontrols
$('#testlink').click(function () {
$(this).parent().newmodelcontrols('number1');
}); // end testlink click function
}); // end ready

Need help understanding Javascript setinterval and function declaration

I am very new to js and jquery and need help understanding why this script does not work. I've checked it over any number of times, but in all my research, there is something that I am missing. Any help would be appreciated. The code should just set text value in div once every 2 seconds. I cut this code down from its real functionality so ignore the fact that it does nothing. Forgive and correct me if I am not posting this properly. It's my first post.
code below:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript">
</script>
<script type="text/javascript">
var test=0;
var timer = setInterval(save_it(), 2000);
var test=0;
$(document).ready(function(){
var save_it = function(){
testdiv.innerhtml = test++;
};
});
</script>
</head>
<body>
<div id="testdiv"></div>
</body>
</html>
Try this example (jsFiddle http://jsfiddle.net/Br59d/)
HTML:
<div id="testdiv"></div>
javascript:
var test=0;
$(document).ready(function(){
var timer = setInterval(save_it, 2000);
});
function save_it(){
$('#testdiv').html(test.toString());
test++;
};
To provide some input:
var save_it = function() {
and
function save_it() {
act two separate ways. If you use var save_it = function() you can't call that function before the declaration.
i.e. you couldn't do this:
save_it();
var save_it = function() {
alert('k');
}
however, if you use function save_it() you can.
save_it();
function save_it() {
alert('k');
}
JSFiddle: http://jsfiddle.net/jeffshaver/nmSD6/

I can't figure out how to get my javascript onclick event to work

When I click on the button nothing happens unless I call the function in the html. I am trying to remove all inline javascript. I have included the commented-out section of html that works. Thanks in advance for the help!
JavaScript:
var welcomeString;
const TEST = 1;
function setWelcomeString() {
"use strict";
welcomeString = prompt("Please enter your name: ", "nobody");
}
function writeOutput() {
"use strict";
document.getElementById("demo").innerHTML = "Hello, " + welcomeString;
}
function main() {
"use strict";
setWelcomeString();
document.getElementById("sayHi").onclick = writeOutput();
}
main();
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>**SET TITLE**</title>
<link href="css/style.css" rel="stylesheet">
<script src="firstScript.js"></script>
</head>
<body>
<h1 id="wiggles">TEMPLATE</h1>
<!--<button id="sayHi" onclick="writeOutput()">Say Hi</button>-->
<button id="sayHi">Say Hi</button>
<p id="demo"></p>
</body>
</html>
When you assign a function as a handler for an event, you need to assign the function itself, not execute the function and assign it's return value as you are doing. Change this:
document.getElementById("sayHi").onclick = writeOutput(); // parens
To this:
document.getElementById("sayHi").onclick = writeOutput; // no parens
Here is a jsfiddle link with a working example.
You have to add your whole code inside load, like this
window.load = function(){
// your javascript here
};
Also, as jbabey mentioned, use either
document.getElementById("sayHi").onclick = function(){ writeOutput();};
Or
document.getElementById("sayHi").onclick = writeOutput;
You have two issues.
The first being covered by jbabey.
The second is that firstScript.js appears before your button. This is problematic as when you are assigning the onClick handler to it. It doesn't exist in the dom.
Try putting the entire main script inside window.onload = function () { ... } or moving it to the bottom of the markup.

Detaching and AppendingTo on Window Resize

So I am trying to detach and appendTo a div based on window size. The following is what I currently have.
I am creating a function with a variable SOCIALBAR assigning it equal to #SOCIALMEDIA and detaching it. Then based on window size for (document).ready and (window).resize, I call the SOCIALBARPlACEMENT function and #SOCIALMEDIA is either appendeto the #TOP or #LEFT divs.
This works fine and dandy on (document).ready but does not work for (window).resize.
In fact, if I remove document.ready, and leave window.resize, the function still runs on page load, but doesn't work on page resize.
Any thoughts would be appreciated. Thank!
function socialbarplacement() {
var socialbar;
socialbar = $("#socialmedia").detach();
if (jQuery(window).width() < 1384) {
socialbar.appendTo("#top");
} else {
socialbar.appendTo("#left");
}
};
$(document).ready(socialbarplacement());
$(window).resize(socialbarplacement());
You are calling the functions immediately rather than passing them as event handlers, try:
$(document).ready(socialbarplacement);
$(window).resize(socialbarplacement);
/*
someFunction() <-- invokes the function and resolves to the returned value
someFunction <-- resolves to the function reference
*/
I would probably do something along these line (untested code):
$(window).resize( function(){
var wnd = $(window), soc = $('#socialmedia');
return function(){
// might add a check to make sure you are not appending to the current parent.
soc.appendTo( $(window).width() > 1384 ? '#left' : '#top');
}
});
Resize will get fired when the page loads so you don't need to have both on ready and resize.
Also looking at it, you are executing the method when you really should be passing it in by name.
I,ve try like this... Enjoy!
$(function () {
if (matchMedia) {
var mq = window.matchMedia('(max-width: 1384px)');
var socialmedia = $("#socialmedia");
mq.addListener(WidthChange);
WidthChange(mq);
}
function WidthChange(mq) {
if (mq.matches && socialmedia) {
socialmedia.appendTo("#top");
socialmedia = null;
} else {
socialmedia = $("#socialmedia").detach();
socialmedia.appendTo("#left");
}
};
});
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="top">
<div id="socialmedia">SOCIALMEDIA</div> <br>
**TOP**
</div>
<div id="left">
<br>
**LEFT**
</div>
</body>
</html>

Categories

Resources