Get value from one click event to other event in JavaScript - javascript

I have code written by other like this.
<button onclick="javascript:confirm("Are you sure?");" id="confirm_button"/>
Now, to add more functionality to this button I am attaching one click event to the same button
$("#confirm_button").live("click",function(event){
//Need value from the confirm box.
//code goes here.
});
How to get the value from the first event in the event listener? I need if for my code to work.
The one way is that I have to move this confirm box into my click event listener, But requirements don't allow me.
Thanks

You can declare a global variable and the store value ion that,so it can be used in other functions
somewhat like this
<script>
//global variable here
var testvariable;
function1
{
//initalize value here
}
function2
{
//use here
}
</script>

Global Scope variables might help you with your problem. If a variable is declared outside a function, then that variable exists on the global object.
Check this link.you will get an pretty lot of information about the various scopes.. :)
<script>
var globalVariable= "someValue";//Use this variable anywhere u may need..
</script>
http://learn.jquery.com/javascript-101/scope/

Use confirm inside jquery Something like this:
$("#confirm_button").live("click",function(event){
var valid = confirm("Are you sure?");
if(valid){
//do something
var myVal = $("YOUR SELECTOR").val(); // to get the value of your selector.
}else{
// do something else
}
});

try this...
$("#confirm_button").live("click",function(event){
var isvalid = confirm("Are you sure?");
if(isvalid){
// to get the value of your selector.
}
else
{
// do something else
}
});

<input type="button" onclick="var tmp=confirm('Are you sure?');if(tmp) foo(); "
id="confirm_button" value="btn"/>
//and in javascript function write ur code
function foo()
{
alert('add functions');
}

Related

Storing previous event.target.id in a variable

I am in a situation where I need to keep track of the previously clicked event.target.id that is firing the click event.
A very simple example of my code is as follows (I am using dojo and jQuery):
on(dom.byId("div-tools-draw"), "click", function (evt) {
var lastActiveTool = evt.target.id;
}
This code keeps overwriting the lastActiveTool variable with the current event id. However, I need a way to keep track of the previous one.
Sorry if this is a silly question, I am still learning JS.
var lastActiveTool;
on(dom.byId("div-tools-draw"), "click", function (evt) {
//do whatever you want with previous value if there is one
lastActiveTool = evt.target.id;
}
Firstly you shouldn't declare your variable inside the function as it'll only be accessible inside that function and since it's an anonymous function, it'll be destroyed each time the function is done running.
var lastActiveTool;
on(dom.byId("div-tools-draw"), "click", function (evt) {
if(typeof lastActiveTool !== 'undefined'){
//Do what you need to do with the last id. Add an else if you want something special to happen when the first element is clicked and there is no previous id.
}
lastActiveTool = evt.target.id;
}

Variable as eventListener named function expression name

I'm writing an awesome IIFE and want this to be as easy as possible for my users who use it. So I was thinking since some of them don't know that to easily remove an eventlistener without it already being a function we can give that inline function a name
Example
document.addEventListener('click',function dood(){
//some function
},false);
document.removeEventListener('click',dood,false);
//instead of
function dood(){
//some function
}
document.addEventListener('click',dood,false);
document.removeEventListener('click',dood,false);
But since they shouldn't know the name exactly I was wondering if we could do
var k = "name_of_function";
document.addEventListener('click',function window[k](){
//the function
},false);
Though I know this does not work is there a way to do this? I'd like to make it so they can easily do this
object.cancel('name_of_function') //which will be the name of the instance
// they created earlier if they gave that instance a name
object={
cancel:function(nm){
document.removeEventListener(self.trigger,window[nm],false);
//self.trigger really is this.trigger which they assign as either scroll,click,mousemove,etc.
}
};
Any ideas? Or is this not possible at all?
usage is:
scrollex('element',{
max:500,
min:500,
pin:200,
offset:0.5,
name:'google',//this then would be used in multiple instances
});
scrollex.events //shows all events and their names
scrollex.listen('google'); //it'll console log all info for this event
scrollex.cancel('google');
I think you're on the right track. But you should not use window, and some local object instead. And dynamically naming function expressions (or whatever that function window[k](){} was supposed to mean) is impossible a pain - don't try this. Just let them stay anonymous, and reference them only via property names / variables.
var object = (function() {
var listeners = {
name_of_function: function dood(){…}
};
document.addEventListener('click', listeners.name_of_function, false);
return {
cancel: function(nm) {
document.removeEventListener('click', listeners[nm], false);
}
};
}());
// now, you can
object.cancel('name_of_function')

How remove function from this code after first usage this field?

$(document).ready(function(){
$('#id_laufzeit_bis').datepicker().on('changeDate', recalculate_deadline);
$('#id_kuendigungsfrist').change(recalculate_deadline);
$('#id_kuendigungsfrist_type').change(recalculate_deadline);
$('#id_kuendigung_moeglichbis').change(check_reminder_date);
$('#id_erinnerung_am').datepicker().one('hide', check_reminder_date);
});
How remove check_reminder_date function from this code after first usage this field? (#id_erinnerung_am)
$('#id_erinnerung_am').datepicker().one('hide', check_reminder_date);
I think this way:
$('#id_erinnerung_am').datepicker().one('click', check_reminder_date);
or might be this one:
$('#id_erinnerung_am').datepicker().end().one('click', check_reminder_date);
hide is not an event use click instead.
Edit Oh, this is what .one() should already do. It probably just didn't fire as one of the others already pointed out.
You can set a flag that indicates if the function has already been called previously.
var isFirstCall = false;
function check_reminder_date(){
if (isFirstCall) {
isFirstCall = false;
//do stuff
}
}
Use this trick to achieve what you want:
//caching the object with id #id_erinnerung_am
var id_erinnerung_am=$('#id_erinnerung_am');
//triggering an event on every close of the datepicker
id_erinnerung_am.datepicker({onClose:function(){
id_erinnerung_am.trigger('datePicker.hidden');
});
//binding the event once with the function 'check_reminder_date',
// this function will be executed only once
id_erinnerung_am.one('datePicker.hidden', check_reminder_date);

jQuery focus blur pass parameter

I can't seem to access the variable defaultValue down in my .blur() function. I've tried various stuff but with no luck. So far I only get an empty object. What's wrong?
jQuery(document).ready(function(){
jQuery('#nameInput, #emailInput, #webInput').focus(function(){
var defaultValue = jQuery(this).val();
jQuery(this).val("");
})
.blur(function(defaultValue){
if(jQuery(this).val() == ""){
jQuery(this).val(defaultValue);
}
});
});
Looks like the question is about the passing data into the .blur or .focus event.
per jQuery API - http://api.jquery.com/blur/
blur( [eventData ], handler(eventObject) )
So if you want to pass data - you can send a parameter to event - which will appear as data in event object.
see this fiddle for more info
http://jsfiddle.net/dekajp/CgP2X/1/
var p = {
mydata:'my data'
};
/* p could be element or whatever */
$("#tb2").blur(p,function (e){
alert('data :'+e.data.mydata);
});
Because your code is wrong :-) you define var inside function (var defaultValue) which is then immediately wiped out.
There are two solutions: define your var as a global var before you bind blur event, or store it in the data of object liket his (which I recommend):
$(document).ready(function(){
$('#nameInput, #emailInput, #webInput').focus(function(){
$(this).val("").data('defaultValue',jQuery(this).val());
}).blur(function(defaultValue){
if($(this).val() == ""){
$(this).val($(this).data('defaultValue'));
}
});
});
It seems to me that you don't understand the basics of JavaScript.
First of all variables in JS are localized to function's scope, so you can't declare variable with var in one function and access it in other function
Second, you can't pass anything to DOM-event handler, except event-object, this is defined by the DOM specification, sometimes you can use event data parameter to the blur jQuery method.
Try this:
jQuery(document).ready(function(){
var defaultValue;
jQuery("#nameInput, #emailInput, #webInput").focus(function(){
defaultValue = jQuery(this).val();
jQuery(this).val("");
})
.blur(function(){
if(jQuery(this).val() == ""){
jQuery(this).val(defaultValue);
}
});
});
First of all, you need to distinguish blur method (function) and handler (function) which is the argument to the blur. You was trying to pass the defaultValue exactly to handler, but that can't be done. Inside handler the defaultValue would be equal eventObject, so you can do smth like console.log(defaultValue.timeStamp) and you'll see smth like 123482359734536
In your approach you can't even use event.data argument to the blur cause it will be set at the time of blur's call (attaching handler). You need to declare a var outside of the both handlers, so it will be visible to both of them
You may consider to read some comprehensive book on JS.
I read "Professional JaveScript For Webdevelopers" by Nicolas Zakas. There is a new edition

Javascript: Can I avoid closures?

I am trying to make an website. I am putting addEventListener to more elements in a function called more times:
idImag = 0;
function function1()
{
//do something
function2()
}
function function2()
{
//do something
document.getElementById("holder" + idImag).addEventListener('mouseover',function(){
idImag++;
alert('It works');
}
function3(event)
{
alert(3);
}
function1();
function1();
<div id="holder0">Dog</div>
<div id="holder1">Chicken</div>
<div id="holder2">Cow</div>
But there is a problem: Only the last element gets the event listener... the others do nothing after putting the mouse over it.
Then I've googled a little and found out about closures and how variables are kept even after function returned... I didn't understand everything, but I just want to find out how to put the event listeners in function2. Can you help me?
Probably you noticed: I am a newbie. Sorry if the question is stupid or if it has no sense. If you need more details, I will put my whole code, but it has variables and comments in Romanian, so I am not sure if you will understand it. Sorry for my bad English and thank you in advance.
Why not a for loop?
function function3 (event) {
alert(3);
}
for (var idImag = 0; i< numberOfHolders; i++) {
//do something1
//do something2
document.getElementById("holder" + idImag).addEventListener('mouseover',function3);
}
It looks like you just care about the image id, which is available through the id attribute of the element.
Thus you can do:
document.getElementById("holder" + idImag).addEventListener(
'mouseover',
function(){
var id = this.id;
/* Then strip off "holder" from the front of that string */
}
);
This looks correct, in that it will call document.getElementById("holder0").addEventListener(…), then it will call document.getElementById("holder1").addEventListener(…). Closures aren't your problem there.
You can verify this by, eg, using console.log to log the element that you're adding the event listener to (you'll need Firebug installed, or Chrome's developer console open).
Maybe paste the code to http://jsfiddle.net/ so we can try it?

Categories