When using onclick in JavaScript to call the function nowClicked(), I need to click the object twice in order for the alert to show. Below is the code for my function.
function nowClicked() {
$('.object').click(function() {
$('.object').removeClass("clicked");
var myClass = $(this).attr("id");
alert(myClass);
$(this).addClass("clicked");
e.stopImmediatePropagation();
});
};
What is the problem?
Here's what happens the first time you click your button:
nowClicked is called because you've set it up on the button's onclick
nowClicked sets up a jQuery click handler for .object
The code inside the jQuery click handler only runs the next time you click on the button.
It looks like you are mixing up two ways of handling clicks -- one is using the onclick event, and the second is using jQuery. You need to pick one and stick to it instead of using both.
There is no need to put it inside another function,because click is itself handling a callback function.Remove the outer function nowClicked else remove the $('.object').click(function() {.In the second case you may to pass the context as a function argument.
$('.object').click(function() {
$('.object').removeClass("clicked");
var myClass = $(this).attr("id");
alert(myClass);
$(this).addClass("clicked");
e.stopImmediatePropagation();
});
Related
I wrote some code for a custom confirm box that calls a function when confirm button (yes-button) is pressed and passes another function as a parameter and I bind it to 2 different button clicks with different functions as a parameter. For example:
$('#button1').click(function() {
callFunction(function() { alert("test"); });
});
$('#button2').click(function() {
callFunction(function() { alert("test2"); });
});
function callFunction(callback) {
//code to display custom confirm box
console.log(callback);
$('.confirm-box .yes-button').click(function() {
callback();
});
}
Everything happens as expected, confirm box appears and on confirm button click I get a callback function executed and it alerts "test" (or "test2" depending on which button called the confirm box). The problem arises when I click button1 that sends a function that alerts "test", then instead of confirming I cancel that (nothing happens as expected), and then click button2 that passes alert("test2") as a callback function. Now once I press the yes-button instead of alerting just "test2", I get both "test2" and "test" alerts even though that console.log I wrote logs just the function that alerts "test2" at the time of that button2 click. It seems like these callback functions get stacked somewhere, but I don't understand where and why.
The .click() function can add more than one handler to an element, and I think that's what's happening here. Try this:
// ...
$('.confirm-box .yes-button').unbind('click').click(function() {
callback();
});
This removes any previous click handler before applying the new one.
When you execute the code:
$('.confirm-box .yes-button').click(function() {
callback();
});
you are binding an event handler to the .yes-button element. If you run that code twice, it will have two events bound to it. And so on.
One solution is to use .one instead, so that the event handler will be removed after the first time it is fired:
$('.confirm-box .yes-button').one("click", function() {
callback();
});
This of course has issues if there are two confirm boxes open simultaneously or if there are two .yes-button elements, but for a simple use case it works fine.
What is happening is that each time a button is clicked the callFunction method is executing. It runs through that code block and applies an event listener to the $('.confirm-box .yes-button') button. So clicking your button N times will apply the click listener N times as well. One solution is to store the function in a variable.
Not sure what the end goal is, but this is one solution.
Another solution would be to remove buttons event listeners each time.
var functionToCallOnYes = function() {};
$('#button1').click(function() {
functionToCallOnYes = function() {
alert("test");
};
});
$('#button2').click(function() {
functionToCallOnYes = function() {
alert("test2");
};
});
$('.confirm-box .yes-button').click(function() {
console.log(functionToCallOnYes);
functionToCallOnYes();
});
You can do it by setting an identity by classes,
var button = $('.confirm-box .yes-button');
$('#button1').click(function() {
button.removeClass("b").addClass("a");
});
$('#button2').click(function() {
button.removeClass("a").addClass("b");
});
button.click(function() {
if($(this).hasClass("a")){
callBackForButton1();
} else {
callBackForButton2();
}
});
It is a bad practice to stack up the event handler for a single element.
Yes, extra callbacks are getting stacked up. In $('button1').click(f), the function f will be called with no parameters every time button1 is clicked. In this case, f is callFunction-- a function that itself attaches a new handler to any .confirm-box .yes-button element each time it's invoked. So on the Nth click, you should have N-1 alerts.
To make things like this easier, you can refer to functions by name in JavaScript. So if you had function test() { console.log("test"); };, you could write $(".confirm-box").click(test) just once and every click on a .confirm-box from then on would print test to the console.
Usually if you have callbacks whose sole purpose is to call a callback, you can just remove that callback.
Take the following code,
// Update button clicked
function updateEntity(e) {
e.preventDefault();
var name = $(this).attr("name");
...
// some stuff
...
}
$(document).on("click", ".updateEntity", updateEntity);
Currently I have this for (go figure) updating an entity I've editted on button click. Now, its parameter is particularly expecting a jQuery event. However, I want to also be able to call this function (end goal: to minimize code) outside of a jQuery event. Like so,
// Do an update but then redirect to prevent adding the same estimate twice.
function createEstimate(e) {
updateEntity(e);
var link = $(this).attr("href");
window.location.href = link;
}
$(document).on("click", ".createEntity", createEstimate);
Question: How would I go about calling updateEntity or setting the function up, so that I can supply it to the click-event handler and call it like a function and still have it used correctly? Is this goal realistic or should I be structuring this differently if I want to achieve such a goal?
(Encase it is not obvious, my current problem is that on the function call updateEntity(e); $(this) becomes window instead of the clicked link.)
Use .call to set this correctly:
updateEntity.call(this, e);
Learn more about this.
div.onclick = function(data, dom) {
return function() {
if (data.seenAlready == true) { // HACK
$(this).children().toggle();
return;
}
recursiveSearch(data, dom);
// after this onclick, I want to assign it to a toggle like function. no clue how to do it.
}
}(child, mycontainer.appendChild(div));
I'm trying to swap the onclick method after first onclick on a dom element. I've just not had any success, it seems to some sort of closure loss, or something. I'm fine using jQuery.
You have two ways to do this and both ways are by using a jQuery function:
1) Use one API method - this will work just once. You will click it once and then you choose your own second handler and the first one will not fire again e.g.
$(myselector).one(function(){
$(this).click(myotherhandler);
});
Here is the link to this API http://api.jquery.com/one/.
2) You can choose the following way to replace the event handler .
$(myselector).click(function(){
$(this).off();
$(this).click("secondhandler");
});
this will turn the first handler off and will just fire second handler
Check this jsbin:
http://jsbin.com/fekuq/1/edit?html,js,output
There is a link in my webpage, the link itself triggers a function that I could not modify, but I want to make the link, when clicked, also calls another JavaScript function at the same time or preferably after the first function is done. So one click to call two functions...could it be implemented? Thanks
<a title="Next Page" href="javascript:__doPostBack('Booklet1','V4504')">Next</a>
is the sample tag I want to modify, how could make it also call "myFunc" at the same time or preferably after _doPostBack is done.
P.S. the function parameter for _doPostBack such as V4504 is dynamically generated by the ASP user control. So I cannot simply treat it as a static function and bind it with another. I think I could only append some function to it? Unless I parse the whole page first and extract the function name with its current parameters...Since every time I click the link, the parameter such as V4504 changes its value....
Thanks!
You should be able to attach multiple event handlers to a single anchor tag, either with .onclick or .addEventListener('click', function)
https://developer.mozilla.org/en/DOM/element.addEventListener
You can attach a handler to an element click event using plain Javascript in such a way:
function hello()
{
alert("Hello!")
}
var element = document.getElementById("YourAElementID");
if (element.addEventListener)
{
element.addEventListener("click", hello, false);
}
else
{
element.attachEvent("onclick", hello);
}
It supprots all common browsers.
Yes, you can do this MANY ways (I use both $(this) and $('identifier') as you don't say how the functions are bound) :
$(this).click(function(){
my_function_1();
my_function2()
});
Or
$('my element').click(function(){
my_function_1();
});
$('my element').click(function(){
my_function_2();
});
Or, if the functions reside on another object:
$(this).click(function(){
my_function_1();
$('#other_element_id').trigger('click'); //there are a bunch of syntaxes for this
});
Sans JQuery, you can use:
var myObj = document.getElementById('element name');
myObj.addEventListener('click', function(){
alert('first!');
});
myObj.addEventListener('click', function(){
alert('second!');
});
Clicking will result in two sequential alert prompts
Once again I've inherited someone else's system which is a bit of a mess. I'm currently working with an old ASP.NET (VB) webforms app that spits JavaScript onto the client via the server - not nice! I'm also limited on what I can edit in regards to the application.
I have a scenario where I have a function that does a simple exercise but would also need to know what item was clicked to executed the function, as the function can be executed from a number of places within the system...
Say I had a function like so...
function updateMyDiv() {
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
how could I get the ID (for example) of the HTML element that was clicked to execute this?
Something like:
function updateMyDiv() {
alert(htmlelement.id) // need to raise the ID of what was clicked,
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
I can expand on this if neccessary, do I need to pass this as an arguement?
The this keyword references the element that fired the event. Either:
<element onClick="doSomething(this);">
or
element.onclick = function() {
alert(this.id);
}
Bind your click events with jQuery and then reference $(this)
$('.myDivClass').live('click', function () {
updateMyDiv(this);
});
var updateMyDiv = function (that) {
alert(that.id);
// save the world
};
You don't need to pass "this", it is assigned automatically. You can do something like this:
$('div').click(function(){
alert($(this).attr('id'));
})
Attach the function as the elements event handler is one way,
$(htmlelement).click(updateMyDiv);
If you are working with an already generated event, you can call getElementByPoint and pass in the events x,y coords to get the element the mouse was hovering over.
$('.something').click(function(){
alert($(this).attr('id'));
});
You would need to pass it the event.target variable.
$("element").click(function(event) {
updateMyDiv($(event.target));
});
function updateMyDiv(target) {
alert(target.prop("id"));
}
Where is your .click event handler? Wherever it is, the variable this inside of it will be the element clicked upon.
If you have an onclick attribute firing your function, change it to
<tag attribute="value" onclick="updateMyDiv(this)">
and change the JavaScript to
function updateMyDiv(obj) {
alert(obj.getAttribute('id')) // need to raise the ID of what was clicked,
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
use the .attr('id') method and specify the id which will return what you need.