Get the latest value of a variable only - javascript

I have this code that creates a random number when click on the button (set number)
Then when you click on the other button (get number), it will retrieve the random number on alert
jQuery('.button1').on('click',function (){
var num = Math.random();
jQuery('.button2').on('click',function (){
alert(num);
});
});
Code in action http://jsfiddle.net/Jim_Toth/dYTEq/
The problem I'm facing is that when the user clicks on (set number) again to get a new number. Then clicks on (get number) the alert retrieves twice with the old number and the new number. If clicked them for the third time it will retrieve triple.
How do you retrieve the latest random number only?

You have your .button2 click handler defined inside your .button1 click handler. Make the num variable global and set it in the first, and then alert it in the second.
var num;
jQuery('.button1').on('click',function (){
num = Math.random();
});
jQuery('.button2').on('click',function (){
alert(num);
});
See a working version here: http://jsfiddle.net/j8zGP/

Try
fiddle Demo
var num;
jQuery('.button1').on('click', function () {
num = Math.random();
});
jQuery('.button2').on('click', function () {
alert(num);
});
Problem
You are adding click handler in the .button1 click on .button2 so it is attached multiple times that's why you get many alerts

The problem is that with each click of button1 you are adding a new event handler to button2. Each time button2 is clicked it will run all attached event handlers, and that will be the same amount as the number of times your click button1.
Try separating your event registrations and use a global variable so both functions can access it...
var num;//global variable can be accessed by both functions
jQuery('.button1').on('click',function (){
num = Math.random();//sets the global variable ready to be used by other functions
});
jQuery('.button2').on('click',function (){
alert(num);//alerts the global variable, as set by the other function
});
Here is a working example

Don't use closures for this.
var num;
jQuery('.button1').on('click',function (){
num = Math.random();
});
jQuery('.button2').on('click',function (){
alert(num);
});

http://jsfiddle.net/dYTEq/2/
var num;
jQuery('.button1').on('click',function (){
num = Math.random();
});
jQuery('.button2').on('click',function (){
alert(num);
});

The problem is, that you are adding the click event handler to the second button multiple times. Your code basically says "When button1 is clicked, add a click event handler to button2". But a new click event handler won't rmeove already existing click event handlers.
You could do this:
(function () {
var num;
jQuery('.button1').on('click', function (){
num = Math.random();
});
jQuery('.button2').on('click', function (){
alert(num);
});
}());
This way each event handler is only attached once. I added the function around that code so num won't be in the global (i.e. window) scope.

Related

How to pass a value from textbox into a jQuery function?

I'm trying to figur out how I can set the var number and then use it in my other function Custom.init(number); and make it stay on the page.
//Set number onclick
function setVar() {
var number = document.getElementById("textbox").value;
//Pass in number
jQuery(document).ready(function() {
Custom.init(number);
});
};
If you're using jQuery, the ready function should wrap all other functions as it will be invoked first and foremost.
$(document).ready(function(){
var number = document.getElementById("textbox").value;
//Then do your validation here
var setVar = function(){
Custom.init(number);
//whatever else is involved with this
}
})
If that doesn't work I'd check the console for a specific error and ensure your Custom.init function is working as expected.
It doesn't make sense to hide the ready handler inside a function. The comments in your code do also suggest that you wish to call Custom.init in response to a mouse click on some element. You would register an event handler to this end.
A suggested streamlining:
//Set number onclick
$(document).ready(function() {
$(<selector for clickable elements>).on (
"click"
, function (eve) {
Custom.init(parseInt($("#textbox").val()));
1;
}
);
});

pass through current target name to function

I'd like to dynamically create event listeners for multiple buttons, and subsequently, show a particular frame label depending on the button clicked, but I'm unsure what to pass through (FYI, this is will be used for HTML5 canvas in Flash CC, but principally the same should apply to a web page for showing divs etc). I currently have this:
var butTotal = 4;
var selfHome = this;
function createListeners () {
for (var i=0; i<butTotal; i++) {
selfHome["btn" + i].addEventListener('click', openPop);
}
}
function openPop () {
alert("test");
selfHome.gotoAndPlay("pop"+event.currentTarget.name.substr(3));
}
createListeners();
It creates the listeners fine, but I don't really know where to start with passing through the current button instance name to tell it which frame label to gotoAndPlay.
Based on the code that you have, I'd simply change the .addEventListener() to call a generic function (rather than openPop, directly), and pass it the reference to the button. So, this:
selfHome["btn" + i].addEventListener('click', openPop);
. . . would become this:
selfHome["btn" + i].addEventListener('click', function() {
openPop(this);
});
At that point, you would then have to update openPop to accept a parameter for the reference to the element that triggered it . . . something like:
function openPop (currentButton) {
At that point, you could reference the clicked button, by using currentButton in the openPop logic.
I'm not sure I totally understand your question. However if you just need to pass the button instance (in you case "selfHome["btn" + i]") you could call an anonymous function in your event handler which calls openPop() with the button instance as an arugment. Would this work for you?
var butTotal = 4;
var selfHome = this;
function createListeners () {
for (var i=0; i<butTotal; i++) {
var currentBtn = selfHome["btn" + i];
currentBtn.addEventListener('click', function(){openPop(currentBtn);} );
}
}
function openPop (btn) {
alert("test");
selfHome.gotoAndPlay(/*use button instance 'btn' to find frame*/);
}
createListeners();
When the event is triggered the this keyword inside the handler function is set to the element is firing the event EventTarget.addEventListener on MDN. If the button have the data needed to be retrieved just get it from the this keyword:
function openPop (btn) {
alert(this.name);
/* ... */
}
It looks like you expect it to contain the function gotoAndPlay() as well as the btn elements (which contain both an ID (of btn[number]) and a name with something special at substr(3) (I assume the same as the id). If those things were all true, it should work in chrome... in other browsers you'll need to add event to the openPop() method signature.
function openPop (event) {
alert("test");
selfHome.gotoAndPlay("pop"+event.currentTarget.name.substr(3));
}
I believe this is what you are looking for and adding that one word should fix your problem (assuming some things about your dom and what selfHome contains):
JSFiddle
You could also leave out the event from openPop() and replace event.currentTarget with this:
function openPop () {
alert("test");
selfHome.gotoAndPlay("pop"+this.name.substr(3));
}
JSFiddle

How do I pass local variable value from one function to another?

In my script I have 2 functions. First function references to a div element, creates a paragraph element inside div and appends some text to this paragraph element;
In my second function is triggered by onclick event attached to a link element. I want the text in the div to be changed to another text when clicking on the link. I do realize that there are 2 options how to achieve this:
1) declare global variables and use them in my second function;
2) pass the variable value from first function to the second function and manipulkate this value from the second function
But the question is how to do I correctly pass the variable value from first function to second function:
Here is the code:
<a href=''onclick='change();return false;'>Change</a>
<div id='box'></div>
Javascript:
window.onload= function createEl(){
var el = document.createElement('p');
var x = document.getElementById('box');
var text = 'text';
el.appendChild(document.createTextNode(text));
x.appendChild(el);
}
function change(){
x.innerHTML="other text";
}
in general you can write this:
function one(){
var var1 = "hello";
two(var1);
}
function two(x){
alert(x);
}
this will alert "hello".
For what you're doing, I would register my events through code to make it easier to pass a variable. We want to use an argument in the event handling function to pass the data to it.
window.onload = function()
{
// do your normal stuff with creating elements
var anc = document.getElementById('ID of your a element here');
if(anc.attachEvent)
{
//code for ancient IE
anc.attachEvent('onclick', function(){change(x);});
}
else if(anc.addEventListener)
{
//code for modern browsers
anc.addEventListener('click', function(){change(x);});
}
}
function change(elem)
{
elem.innerHTML='other text';
}
Do note that older versions of IE don't recognize addEventListener and use attachEvent instead, as seen in the above if block. Here's the documentation for addEventListener.

jquery function for 2 events

In the following jquery, it works when I finish typing a value (keyup) in a textbox:-
<script type="text/javascript">
$(function(){
var minTenderNum;
$("#tenmoney").keyup(function(){
var minTenderMoney = $(this).val();
if(minTenderMoney <=1000)
minTenderNum = 3;
else if(minTenderMoney > 1000)
minTenderNum = 5;
$('#sunum').children().remove().end();
maxTenderNum = minTenderNum + 4;
for(var i=minTenderNum;i <=maxTenderNum;i++)
$('#sunum').append(new Option(i, i, true, true));
$("#uniform-sunum>span").html('');
});
});
</script>
<select id="sunum" name="sunum">
</select>
sometimes, a value already exists when the page is onload, but I have to modify the value and "key up" so that the function starts again.
If I wish to include an event for on load, how shall I modify the function? Thanks!
one of the ways to do this is On document ready You can fire a keyup event like this
$("#tenmoney").trigger('keyup');
add this line inside document ready callback
$(function(){
});
or even beter just call $.keyup() without any argument which will trigger keyup event on that element like this
$("#tenmoney").keyup();

assigning click method to variable

I am creating an array & assigning the value to each index in a function through variables.
I also want to attach a jquery click method to each variable. However, I am getting 'undefined' in return when the click method is called.
var i = 0;
var eCreditTransactions = new Array(6); // 6 members created which will be recycled
function abc()
{
addingElements (i);
}
/* **** THE FOLLOWING IS THE PROBLEM AREA **** */
$(eCreditTransactions[i]).click (function () // if user clicks on the transaction box
{
creditTransactionSlideIn (eCreditTransactions[0], 150); //another function called
});
/* **** this is the function being called in the first function above **** */
function addingElements (arrayIndex) // func called from within the 'createCreditTransaction()' func
{
eCreditTransactions[i] = $(document.createElement('div')).addClass("cCreditTransaction").appendTo(eCreditSystem);
$(eCreditTransactions[i]).attr ('id', ('trans' + i));
$(eCreditTransactions[i]).html ('<div class="cCreditContainer"><span class="cCreditsNo">-50</span> <img class="cCurrency" src="" alt="" /></div><span class="cCloseMsg">Click box to close.</span><div class="dots"></div><div class="dots"></div><div class="dots"></div>');
creditTransactionSlideOut (eCreditTransactions[i], 666); // calling slideOut animation
counterFunc ();
return i++;
}
Try this:
$(document).ready(function() {
$(".cCreditTransaction").click(function() {
//do what you want on click event
});
});
Hope it helps
Given that it looks like each element you're adding to the array has a classname (cCreditTransaction) you can hookup the click events using something like
$(document).delegate(".cCreditTransaction", "click", function() {
// code to fire on click goes here.
});
or in jQuery 1.7+ you can use .on instead of .delegate
You don't then need to hook up n events, but just one event that matches all items in the selector (in your case, the class name)
You should also change $(document) to a container element that has an Id, so that the DOM traversal to find the classes is trimmed down as much as possible. Why? Because finding elements by class name is a relatively expensive procedure, as opposed to finding tags or even better, an ID.
it looks like there should be a loop in this part:
function abc()
{
addingElements (i);
}
there is a call to addingElements, and an 'i' parameter being passed, but 'i' is at that moment still defined as 0.
it should say something like
function abc()
{
for (i=0;i<=7;i++)
{
addingElements (i);
}
}

Categories