Trigger a Jquery function that has $this. onload and onclick - javascript

Trigger a Jquery function that has $this. on window load and on click
function get_div_id(){
var f_id = $(this).attr("id");
alert(f_id);
}
$(window).load(function(){
get_div_id();
});
$('.divs_same_class_diferent_id').click(function() {
get_div_id();
});
As you can deduce, this will not work, but you have an idea of what I'm trying to do, right?

Depending on where that code is it may be running prior to the DOM being created in which case you're attempting to bind event listeners to elements that do not yet exist. try this:
function get_div_id(){
var f_id = $(this).attr("id");
alert(f_id);
}
$(document).ready(function(){
$('.divs_same_class_diferent_id').click(get_div_id);
// notice no anonymous function, this works because
// we're passing in the function object for get_div_id
});

Related

jQuery add event and instantly execute it

Often there is situation when I need to add some event with some customizations and then apply those customizations on page ready.
Usually I was doing it like:
$(window).resize(function(){
//some code
}).resize(); //trigger it when event defined
Problem with this solution is that if I have many resize events, then if I trigger it like this - it will re-execute all previously defined events too.
So another solution could be:
var myCallback = function(){ /*some code*/ };
$(window).resize(function(){
myCallback();
});
myCallback();
And it does it correctly but I find it not so good looking code and also there is no this inside function changed to event target DOM element that is very useful quite often.
Great would be something like
$(window).addEventAndFireOnce("resize", function(){});
such function is not so hard to implement, but I'm wondering if there is something like this there already in js or jQuery.
I don't know if I'm alone in this, but if I need to do that (and it's not uncommon) I bind a custom event name (possibly with a scope) at the same time as I bind the real event ("click" or "change" or whatever):
var myCallback = function(ev) { ... };
$(window).on("resize my-resize", myCallback).trigger("my-resize");
That's particularly useful when you're handling something like a "click" event on a checkbox. Triggering the "click" will actually update the checkbox "checked" state, which is not generally what you'd want to do. There's the jQuery .triggerHandler() method, but for whatever reason that only works on the first element in the jQuery object, so you can't trigger the handlers for all the checkboxes in a form with one call.
I would write it like so:
var myCallback = function(){ /*some code*/ };
$(window).resize( myCallback );
myCallback();
I think what you are looking for here is namespaced handlers
var log = (function() {
var $log = $('#log');
return function(msg) {
$('<p/>', {
text: msg
}).appendTo($log)
}
})();
$(window).resize(function() {
log('handler 1');
});
$(window).resize(function() {
log('handler 2');
});
$(window).on('resize.myspecial', function() {
log('handler 3');
}).trigger('resize.myspecial');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="log"></div>

How can I retrieve the id of element that triggered my function?

I have a function like below;
function myfunction(param1,param2,param3){
alert(param1);
alert(param2);
alert(param3);
alert(buttonid);//i want to alert mybutton here
}
$('#mybutton').click(function() {
myfunction("hi","hello","howdy");
});
The function is evoked using a button click event. I want to alert the button's id in the function called. How can I do this?
The this in your current function is referring to the window object. You want to use the event object (whose target property will refer to the element that triggered the action).
function myfunction(param1,param2,param3){
alert(param1);
alert(param2);
alert(param3);
alert(event.target.id);
}
Also, I would suggest using the jQuery on listener rather than the click listener. This will make the listener AJAX compatible.
$(document).on("click", "#mybutton", function(){
myfunction("hi", "hello", "hey");
});
Try this
function myfunction(param1,param2,param3,buttonid){
alert(param1);
alert(param2);
alert(param3);
alert(buttonid);//i want to alert mybutton here
}
$(document).ready(function(){
$('#mybutton').click(function() {
myfunction("hi","hello","howdy",$(this).attr('id'));
});
})

$(this) referring to window, not div that called function

I have a function that dynamically inserts a close button into divs as they are added to the page.
//Insert Close ALERT WINDOW button
function addCloseAlertButton(){
if ($(".alert").find('.closeAlerts').length < 1){
$(".alert").append('<div class="closeAlerts" onclick="closeAlert()">Dismiss</div>');
}
};
And the function called by onclick:
//Close Alert Function
function closeAlert(){
$(this).parent().remove();
};
But clicking on the div doesn't remove the alert div as I expected. When I console.log($(this)) in the function, I found that $(this) was referring to the entire window and $(this).parent came up empty, so that is why the function isn't working.
Does anyone know why this is happening and how I can make it so $(this) refers to the calling div, not the entire window?
Don't use inline JS to do that. Instead use event delegation:
$(document).on('click', '.closeAlerts', function(){
$(this).parent().remove();
});
Replace your
onclick="closeAlert()"
with this:
onclick="closeAlert.call(this)"
and it should work.
Because you're using inline event handlers. If you want to keep the handler function separate, this would be one possibility:
function addCloseAlertButton() {
if ($(".alert").find('.closeAlerts').length < 1) {
$('<div class="closeAlerts">Dismiss</div>')
.appendTo('.alert')
.click(closeAlert);
}
};
function closeAlert() {
$(this).parent().remove();
};
You can set this as parameter in function
<div class="closeAlerts" onclick="closeAlert(this)">Dismiss</div>
And this will be your div object.
But I'm not reccomend you to use embedded javascript code in html elements. Try to separate js code from html.

click function call with $(this) from another function in javascript/jquery

I have a click function which is given below
$('.page-nav li').click(function(event){
console.log("clickedTab-page-nav-first-before set ="+Session.get('clickedTab'));
Session.set('clickedTab',event.target.id);
//var sel = event.prevUntil("[class*=active]").andSelf();
var sel = $(this).prevUntil("[class*=active]").andSelf(); //find all previous li
//of li which have
//class=active
sel = sel.add(sel.eq(0).prev()); // include the that li also(Now all li elements).
sel.removeClass('active'); //Remove the active.
//sel = event.nextUntil("[class*=active]").andSelf(); //Also for top to bottom
//(Viceversa)
sel = $(this).nextUntil("[class*=active]").andSelf();
sel = sel.add(sel.eq(-1).next());
sel.removeClass('active');
//event.addClass('active');
$(this).addClass('active'); //Now add class active for the clicked li
var rightcontent="";
console.log("clickedTab-page-nav-second-after set = "+Session.get('clickedTab'));
switch($(this).attr('id')){
case 'rfq':
.......
.....
}
});
Then next is I want to call this click function from another place
$(document).ready(function() {
console.log("clickedTab-page load = "+Session.get('clickedTab'));
if(Session.get('clickedTab')!=null||Session.get('clickedTab')!= undefined){
alert("Got It");
//$('.page-nav li').click(event);
$('.page-nav li').click(); //this is not working
}
});
Now the problem is page click function in if condition is not working. However I got the alert. Any help is highly appreciated. Thanks in advance...
you are not really using the event parameter in your function and you state you wish to call it outside of an event chain so you could change it to be a regular function
var setupClicktab = function(id){
console.log("clickedTab-page-nav-first-before set ="+Session.get('clickedTab'));
Session.set('clickedTab',id);
...
}
the you'd use it like:
$('.page-nav li').click(function(event){return setupClicktab(event.target.id);});
and in document ready
setupClicktab.Call($('.page-nav li'),Session.get('clickedTab'));
The latter call class it in the context of the selection (that is this inside the function will refer to the selection(1). It also passes the value stored in the session variable in as the id.
a side note. Your test
if(Session.get('clickedTab')!=null||Session.get('clickedTab')!= undefined)
could simply be
if(Session.get('clickedTab'))
Unless you might store either an empty string, zero or the boolean value false in that variable. But seeing how it's used that's unlikely since they are all invalid values for the id attribute
(1)This is slightly different than in the click event where it refers to the DOM element)
You need to put $('.page-nav li').click(function(event){ inside document.ready and before your $('.page-nav li').click();. Because if you call .click when the DOM is not ready, there are chances that there is no event handler attached
If you don't put $('.page-nav li').click(function(event){ inside document.ready OR you're dealing with dynamically created elements. You need delegated event $(document).on("click",".page-nav li",function(event){
From $.on

Changing the onclick event delegate of an HTML button?

How do you change the JavaScript that will execute when a form button is clicked?
I've tried changing its onClicked and its onclicked child attributes like so:
$('mybutton').onClick = 'doSomething';
and
$('mybutton').attributes["onclick"] = 'doSomething()';
Neither seem to work. My other options are:
To have two buttons and hide one and show the other.
To have it directed to a function that evals a string and change the string to the function I want to execute.
Neither seem very elegant.
I'm using Prototype as a js library so it that has any useful tools I can use them.
If the original onclick event was set through HTML attributes, you can use the following to overwrite it:
$("#myButtonId").setAttribute("onclick", "myFunction();");
For Prototype, I believe that it would be something like this:
$("mybutton").observe('click', function() {
// do something here
});
EDIT: Or, as it says in the documentation, you could simply specify the function you want to call on click:
$('mybutton').observe('click', respondToClick);
function respondToClick(event) {
// do something here
}
But this is all, again, Prototype-specific.
Using the Prototype framework you can do:
Event.observe("mybutton", "click", clickHandler);
or:
Event.observe("mybutton", "click", function() {
alert("Button clicked!");
});
or:
$("mybutton").observe("click", clickHandler);
or:
$("mybutton").observe("click", function() {
alert("Button clicked!");
});
See the Event class documentation
The general way to set an onclick handler in javascript is to set onclick to a function, by passing it the name of a function directly, not in a string. So if myButton is set to a DOM Element, you would write:
myButton.onclick = doSomething;
So when you click the 'mybutton' button, the doSomething function will be called as doSomething(). For anonymous functions, you can write:
myButton.onclick = function() {
alert("myButton was clicked!");
};
In JQuery it's
$("#myButtonId").click(myFunction);
function myFunction(){
alert("Clicked");
}
Or if you want to put the function inline:
$("#myButtonId").click(function(){
alert("Clicked");
});
If you are using JQuery firstly make sure you use the relevant selector prefix (IE: If your using the Id of the element put a # in front of it). Secondly it's the click method to assign a callback to the click event.
Last I used Prototype, it was something like this:
Event.observe('mybutton', 'click', doSomething);
By the way, your examples might've even worked if you didn't quote the function names.
EDIT: Yes, Element.observe(element, eventName, handler) and someElement.observe(eventName, handler) also work. And don't quote the handler name - you want to pass the function not a string!
I found a solution for your issue with prototype under firefox:
$("#myButtonId").writeAttribute('onclick', ''); // first remove the attribute
$("#myButtonId").observe('click', function () { ... }); // then add the event

Categories