Passing Variables Through JQuery Click Functions - javascript

How can I pass a variable from one click function to the other through JQuery?
$(document).ready(function() {
var n = 1;
$('#Next').click(function() {
var nn = n++;
});
$('#Previous').click(function() {
alert(nn);
});
});

As you already have a variable in a higher scope, use that, otherwise data() would be a better approach.
$(document).ready(function() {
var n = 1;
$('#Next').click(function() {
n++;
});
$('#Previous').click(function() {
alert(n);
});
});

Replace
var nn = n++;
with
n++;

Related

jQuery sum of variables

I have this working JS which checks if different checkboxes are or not checked and asigns a different price for each one that will later be summed up.
function priceCandy1() {
var priceCandy1 = 0;
var candy = document.getElementById("candy1");
if(candy.checked==true)
{
priceCandy1=13;
}
return priceCandy1;
}
function calculateTotal()
{
var totalPrice = priceCandy1() + priceCandy2() + priceCandy3();
document.getElementById('totalid').innerHTML = "$" + totalPrice;
}
Now I'm trying to code the equivalent in jQuery and this function does work:
$(function () {
var priceCandy1 = 0;
var candy = $('#candy1');
$('#candy1').on('click',function () {
if (candy.is(':checked')) {
priceCandy1 = 13;
}
});
return priceCandy1;
});
But I can't grab the returned price into a function that will add up every priceCandy#. Out of scope but I don´t know how to fix it.
If it is an issue of scope like you say, you could declare priceCandy1 outside the function, as a global variable.
var priceCandy1;
$(function () {
priceCandy1 = 0;
var candy = $('#candy1');
$('#candy1').on('click',function () {
if (candy.is(':checked')) {
priceCandy1 = 13;
}
});
});
Then use priceCandy1 in your totalPrice function and it should be able to fetch it.
Wrap them in the same function:
$(function () {
var priceCandy1 = function() {
if($('#candy1').is(':checked')) {
return 13;
}
return 0;
},
calculateTotal = function()
{
var totalPrice = priceCandy1() + priceCandy2() + priceCandy3();
$('#totalid').text('$' + totalPrice);
};
calculateTotal();
});

how to execute second method only after first method is executed

I want to print a heading tag only after a paragraph tag is loaded. Below is my Javascript code. See the plunker for more clarification: http://embed.plnkr.co/aheHkSQUBft5A4Z3wkie/preview
function changeText(cont1, cont2, speed){
var Otext = cont1.text();
var Ocontent = Otext.split("");
var i = 0;
function show() {
if (i < Ocontent.length) {
cont2.append(Ocontent[i]);
i = i + 1;
};
};
var Otimer = setInterval(show, speed);
};
$(document).ready(function() {
changeText($("p"), $(".p2"), 30);
clearInterval(Otimer);
});
$(document).ready(function() {
changeText($("h2"), $(".h2"), 30);
clearInterval(Otimer);
});
I would do something like this (please not that ES6 Promises aren't supported by Internet Explorer, but there are shims to use Promises with old browsers too).
You'll have to fill out the parts commented to get it to work though:
var Otimer;
/*#TODO: refactor show() function to use ES6 Promises (eventually with shims) */
function show(Ocontent) {
var i = 0;
if (i < Ocontent.length) {
cont2.append(Ocontent[i]);
i = i + 1;
};
if (Otimer === undefined) {
Otimer = setInterval(show, speed); // Remember to fulfill the promise and remove the interval once it's finished
}
// return the promise
};
function changeText(p1, p2, speed) {
var Otext = p1.text();
var Ocontent = Otext.split("");
return show(Ocontent);
};
$(function () {
changeText($("p"), $(".p2"), 30).then(function() { // We call changeText the second time after the promise return by changeText() is fulfilled and the show() function has finished
Otimer = undefined;
changeText($("h2"), $(".h2"), 30);
});
});
first of all, variable declaring inside of function is scoped variable, which You cannot access from outside of the function.
so the line clearInterval(Otimer); never works.
the code below is fixed code of the scope issue and using callback to implement what you want.
function changeText(cont1, cont2, speed, cb) {
var Otext = cont1.text();
var Ocontent = Otext.split("");
var i = 0;
function show() {
if (i < Ocontent.length) {
cont2.append(Ocontent[i]);
i++;
}else{
clearInterval(Otimer)
if(cb) cb()
}
};
var Otimer = setInterval(show, speed);
};
$(document).ready(function() {
changeText($("p"), $(".p2"), 30, function(){
changeText($("h2"), $(".h2"), 30);
});
});
http://plnkr.co/edit/xowItFUWqI79obi4ZVNV?p=preview

Why are all images be changed to the first input

<script type="text/javascript">
var interval;
$('#105').mouseover(function()
{ mouseOver('105'); });
$('#105').mouseout(function()
{ mouseOut('105') ;});
function mouseOver(videoId)
{ var num = 2;
interval = setInterval(function()
{ $('#'+videoId).attr('src', '../thumbs/268255615/268255615.'+num+'.jpg');
if(num == 12)
{ num = 1; }
else
{ num++; }},500); }
function mouseOut (videoId)
{ clearInterval(interval); $('#'+videoId).attr('src', '../thumbs/268255615/268255615.1.jpg'); }
</script>
<script type="text/javascript">
var interval;
$('#104').mouseover(function()
{ mouseOver('104'); });
$('#104').mouseout(function()
{ mouseOut('104') ;});
function mouseOver(videoId)
{ var num = 2;
interval = setInterval(function()
{ $('#'+videoId).attr('src', '../thumbs/325082397/325082397.'+num+'.jpg');
if(num == 12)
{ num = 1; }
else
{ num++; }},500); }
function mouseOut (videoId)
{ clearInterval(interval); $('#'+videoId).attr('src', '../thumbs/325082397/325082397.1.jpg'); }
</script>
The code above is a JavaScript image rotator. The problem with the code is that the last image path always overwrites the image paths before it.
For example if image path one = thumbs/imagea.jpg and if path two = thumbs/imageb.jpg path one ("thumbs/imagea.jpg")then becomes path two on hover becomes ("thumbs/imageb.jpg")
This script worked at one point trying to figure out what is wrong or been changed any ideas?
This is quite obvious: you are redefining mouseOver as a function. The second time you define it, it overwrites the first function. This is because mouseOver is defined on window-scope. Splitting it up in two blocks does not change that. Also note that "interval" is also being defined twice, so a name clash will also occur here.
A solution would be to either use closures, change the name of one of either functions or merge the two functions into one.
Closures are done by wrapping each script in the following block:
(function() {
// your script here
}());
A merged function would be:
var i, setupImage, images;
images = [
{ "id" : "#104", "prefix" : "../thumbs/325082397/325082397." },
{ "id" : "#105", "prefix" : "../thumbs/268255615/268255615." }
];
setupImage = function (image) {
'use strict';
var interval;
$(image.id).mouseover(function () {
var num = 2;
interval = setInterval(function () {
$(image.id).attr('src', image.prefix + num + '.jpg');
if (num === 12) {
num = 1;
} else {
num += 1;
}
}, 500);
});
$(image.id).mouseout(function () {
$(image.id).mouseout(function () {
clearInterval(interval);
$(image.id).attr('src', image.prefix + '1.jpg');
});
});
};
for (i = 0; i < images.length; i += 1) {
setupImage(images[i]);
}

Unexpected order in script execution

Why is it running the second script and how can I make it work like a toggle control?
<script>
var el = 2;
$(document).ready(function(){
$(".rightDiv").click(function(){
if (el == 2) {
$(this).animate({left:'150px'});
el = 1;
}
});
});
</script>
<script>
$(document).ready(function(){
$(".rightDiv").click(function(){
if (el==1) {
$(this).animate({left:'50px'});
el = 2;
}
});
});
</script>
You only need one .ready()
$(document).ready(function()
{
var el = false;
var rightDivs = $('.rightDiv');
$(rightDivs).click(function(){
if (el == false)
{
$(this).animate({left:'150px'});
el = true;
}
else if (el == true)
{
$(this).animate({left:'50px'});
el = false;
}
});
});
This should work fine for you:
var el = false;
$(document).ready(function() {
$(".rightDiv").click(function() {
$(this).stop(true).animate({left: (el ? 50 : 150) + 'px'});
el = !el;
});
});​
jsfiddle with example
You have atteached two event handlers, so when the event happens it will run one, then the other.
As the first one will change the variable so that the condition in the second one becomes true, the code inside both if statements will run.
Put the code in the same event handler, so that you can use else to run only one of them:
<script>
$(document).ready(function(){
var el = 2;
$(".rightDiv").click(function(){
if (el == 2) {
$(this).animate({left:'150px'});
el = 1;
} else {
$(this).animate({left:'50px'});
el = 2;
}
});
});
</script>
here's a slightly improved version of #h2ooooooo 's answer, where we ditched the global scoped variable and use element's attributes.
Basically what we are doing here is to prevent bloating the global scope by using global variables and now we are working with data directly related to the element that was pressed.
$(document).ready(function() {
$(".rightDiv").attr("isLeft",1).click(function() {
var pos = "50";
if( $(this).attr("isLeft") == "1" ){
pos = "150";
$(this).attr("isLeft",0)
}else{
$(this).attr("isLeft",1);
}
$(this).stop(true).animate({left: pos + 'px'});
});
});

How to combine variables with Jquery?

Got the following code:
$(document).ready(function()
{
$('a.add-item').click(function()
{
if ($(this).parent().find('input').attr('value', '0'))
{
$(this).parent().find('input').attr('value', '1')
}
});
});
What I would like to do is to create a variable and increment it and then add it to my above code replacing .attr('value', '0')) 0
How would I go about this?
thanks,
Keith
You mean like this:
$(document).ready(function()
{
$('a.add-item').click(function()
{
var $item = $(this).parent().find('input');
var value = parseInt($item.attr('value'), 10);
if (!value) {
value = 0;
}
$item.attr('value', value + 1);
});
});

Categories

Resources