jQuery simulate click - javascript

I want to trigger a function when the page is loaded. There are many ways to do this.
However, when I add $('#button').click in front of my function, then the getType function is not recognized. For example:
$('#button').click(function getType(id) {
//...some code
});
error: getType is not defined
What am I doing wrong?
Just to clarify, in this case I cannot use an anonymous function. Also, it does not matter to me whether I use $(document).ready or $(window).bind("load", function(), but using these I still get the “getType is not defined” error.

You either have to make your function anonymous:
$('#button').click(function() {
//...some code
});
Or pass the function itself:
function getType() {
//...some code
}
$('#button').click(getType);
If you just want to trigger a click, call .click():
$('#button').click();
Also, your id parameter won't be the element's id. It'll be the click event object. To get the element's id, you can refer to the clicked element using this:
$('#button').click(function() {
var id = this.id;
});
I suggest you read a few JavaScript and jQuery tutorials (in that order).

You are using the inline notation so, you should use an anonymous function (no name function)
your code should be:
$('#button').click(function() {
// do your stuff here
}
);
Beside that, as the titles says, you need to simulate a click event, right ? if so you better use something like:
$('#button').on('click', function() {
alert($(this).text());
});
// somewhere when you want to simulate the click you call the trigger function
$('#button').trigger('click');
see documentation here

$('#button').click(function getType(id) {
//...some code
});
Should be:
$('#button').click(function() {
[...] code here
}
);
function() { } is a callback with what code have to do when I click some element.
If you have the getType function, you can pass it as a callback:
$('#button').click(getType);
If you want to trigger a funcion, when page load, you can do this:
$('#button').trigger('click');
Or
function getType() {
[...] code here
}
getType();

Use .trigger( event [, extraParameters ] ) on the element.
extraParameters
Type: Array or PlainObject
Additional parameters to pass along to the event handler.
The added benefit is that you can pass data to the event handler, whereas if you use .click(), you cannot assign data to the object.
$("#target").trigger('click');
If you're looking to use the extraParameters:
$( "#foo" ).on( "custom", function( event, param1, param2 ) {
alert( param1 + "\n" + param2 );
});
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );

The .click() method requires a callback function. So you can do something like this instead:
//Define your function somewhere else
function getType(id) {
//...some code
}
$('#button').click(function() {
getType($(this).attr('id')); //Execute it when its clicked.
});

Try this, the id can not be passed the way you do:
$('#button').click(function() {
var id = this.id;
//...some code
});

Related

Google Tag Manager - storing id of a clicked div/button

Looked for the answer all over, tried reading seperatly but couldn't find an answer..
I have a site, on which Google Tag Manager is implemented, and I need to extract the id of a clicked button (or its parent).
this is my code:
function(){
$(document).ready(function(){
var editid;
$('div.uk-button').click(function() {
editid = $(this).attr('data-id');
});
return editid;
});
}
Thanks!
The simplest approach is to create the following custom javascript variable:
function(){
return $({{Click Element}}).attr('data-id');
}
This will return the data-id attribute for all events (including clicks).
Attach this variable to the relevant event tag, and use click class contains uk-button as the trigger.
You can remove the outer function and code like below.
$(document).ready(function () {
$('div.uk-button').click(function () {
var editid;
editid = $(this).attr('data-id');
alert(editid);
});
});
Hey it looks like you may be not be catching the returned value of the document ready callback.
For example, this returns undefined since the return of $(document).ready() callback is not being returned by the containing function:
function testfunc() {
$(document).ready(function(){
var editid = 'this is the return value';
return editid;
});
}
testFunc()
"returns undefined"
I'm guessing that you might be trying to set up a custom javascript variable in GTM. You can still use document ready to ensure the elements are present but the returned value needs to be returned by the outer function for it to be passed into the variable.
So your example should work as follows:
function(){
var editid;
$(document).ready(function(){
$('div.uk-button').click(function() {
editid = $(this).attr('data-id');
});
});
return editid;
}

How to set a jquery on() function only if it doesn't already existis?

I'm calling via ajax additional content where I add a jquery on() function for a click event. Each time I renew the content the event is also set again so at the end it get executed several times. How can I avoid this behavior?
How do I test if the click event is already set on the document?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click
<script>
// first ajax load
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});
// second ajax load
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});
</script>
I already try to just the jQuery.isFunction(), but I don't anderstand how to apply it in this case.
You can Unbind the click event , if you getting more than one time exectuated.
$(document).unbind('click').on("click", ".open-alert", function () {
//do stuff here
});
Or you can also use it
$(document).off("click", ".open-alert").on("click", ".open-alert", function () {
});
Using
$(document).on('click', '#element_id', function() {
//your code
});
Will check the DOM for matching elements every time you click (usually used for dynamically created elements with ajax)
But using
$('#element_id').on('click', function() {
//your code
});
Will only bind to existing elements.
If you use the 1st example, you only need to call it once, you can even call it before your ajax call since it will recheck for matching elements on each click.
<script>
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});
// first ajax load
// second ajax load
...
</script>
In case you cannot bind the event to the specific DOM element (which might happen if you use Turbolinks for example) you can use a variable to check whether you set the event or not.
Local scope
var clickIsSet = false;
// any ajax load
$(document).on('click', '.open-alert', function () {
if ( clickIsSet ) {
alert('hello world!');
clickIsSet = true;
}
});
Global scope
I don't recommend to make clickIsSet global, but in case you are importing/exporting modules you can do that:
// main.js
window.clickIsSet = false;
// any-other-module.js
$(document).on('click', '.open-alert', function () {
if ( window.clickIsSet ) {
alert('hello world!');
window.clickIsSet = true;
}
});
jQuery check if event exists on element : $._data( $(yourSelector)[0], 'events' )
this return all of element events such : click , blur ,
focus,....
Important Note: $._data when worked that at least an event bind to element.
so now:
1.in your main script or first ajax script bind click event on element
<script>
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});
</script>
2. in secound ajax:
var _data = $._data( $('.open-alert')[0], 'events' );
if(typeof _data != "undefined"){
var eventClick = $._data( $('.open-alert')[0], 'events' ).click
var hasEventClick = eventClick != null && typeof eventClick != "undefined";
if(!hasEventClick){
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});
}
}
I get Confuse about your question but as far as understand your question I have three suggestions:
Use Id element (as #Mokun write the answer)
Use Common Function for call functionality instead use through the click event.(Make Sure of function does not overwrite your content by calling).
Use of flag variable (or global variable for your tracking event) in jquery and identify your function call for particular execution.

e.preventDefault(); undefined is not a function

I'm getting the following error that is saying my e.preventDefault(); ---> "e." undefined is not a function when clicking <button class='url_qry_add' onclick='url_qry_add(this);'>. The function itself is defined before the end of my </body> and I have only invoked jQuery once.
The function structure is as follows:
var url_qry_add = function ( e ) {
e.preventDefault();
...
};
It used to be:
$( "ul.url_qry" ).on( "click", "li .url_qry_add", function ( e ) {
e.preventDefault();
...
});
But subsequent buttons added dynamically afterwards were not being picked up.
So I've been trying to figure out how to go about it and decided I should try converting the problem function to a named "invokable" function and putting the call in manually with the onclick='..' into the buttons that exist before and after dynamic creation.
Like I say, the error must be in the way I've created the function or the way I'm calling it. The error can't be to do with the order of files and I have not accidentally nested the function within another function or a document.ready.
What am I doing wrong?
<button class='url_qry_add' onclick='url_qry_add(event);'>
var url_qry_add = function (e) {
console.log(typeof e.preventDefault); // function
};
Update:
I'll try clarify how it works "internally", when we add attributes to function url_qry_add "inside" it looks like this:
document.querySelector('.url_qry_add').addEventListener('click', function (event) {
(function (event) {
url_qry_add(event, this, $(this));
}).call(event.target, event);
});
var url_qry_add = function (event, element, $jElement) {
console.log(event);
console.log(element);
console.log($jElement);
};
Hence, we have variable "event" (event object, where we have method preventDefault and so on), and "this" (current element). I hope that this explanation will help you understand where we get variable "event".

Simple Javascript Calling function not working/don't know how to get it to work

I'm trying to call a function and not the alert and I thought it was as easy as just doing something like this: FunctionsName(); and delete the alert(''); but it's not working for me :(
Can someone please look at the code I have below and tell me what is wrong ?
Thank you so much!!
<script type="text/javascript">
var comper;
function checkComper() {
var onResponse = function(comperNow) {
if (comper === undefined) {
comper = comperNow;
return;
}
if (comper !== comperNow) {
// show a message to the visitor
alert("New Info Added"); // <--*** I WANT TO TAKE THIS OUT AND CALL $("#append").click(function(e)
comper = comperNow;
}
};
$.get('getlastupdate.php', onResponse);
}
var tid = setInterval(checkComper, 2000);
$(function() {
var $table = $("table.tablesorter");
$("#append").click(function(e) {
e.preventDefault();
$.get('updatetable.php', function(data)
{
$table
.find('tbody')
.html('')
.append(data);
$table.trigger("update", [true]);
});
});
/*........ and so on.... */
</script>
What about changin that :
alert("New Info Added");
to that :
$('#append').trigger('click');
It will simulate a click and trigger the function.
One thing important to distinguish:
alert("New Info Added") is a function. Actually, alert() is a function, being passed the parameter "New Info Added".
$('#append').click(function(e) { is not a function, at least, not in the same way. $('#append') is a jQuery selector function, which selects all elements with an id of "append". $('#append').click() is a function that sets a click event on all elements returned in the selector.
What the whole syntax of $('#append').click(function(e) { means is on its own a syntax error. What you're doing is telling the elements found in the selector what their click function should be. But the function(e) { says that it's the start of the code of the function. That line of code isn't complete until the ending }) - the } closing the function declaration and the ) closing the call to click.
So, you can't simply replace alert("New Info Added"), which is a complete function call, with $('#append').click(function(e) {, because it's a syntax error - you haven't completed the function(e) declaration, nor the click function call. You can trigger the click function, as Karl's answer told you. Or, you can use the shortcut:
$('#append').click()
Note that this is a full proper sentence, and can therefore replace the alert.

jQuery: Call a function twice

I'm trying to run a function twice. Once when the page loads, and then again on click. Not sure what I'm doing wrong. Here is my code:
$('div').each(function truncate() {
$(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
});
$('.truncate').click(function() {
if ($(this).parent().hasClass('closed')) {
$(this).parent().removeClass('closed').addClass('open').children().show();
}
else if ($(this).parent().hasClass('open')) {
$(this).parent().removeClass('open').addClass('closed');
$('div').truncate();
$(this).show();
}
});
The problem is on line 13 where I call the truncate(); function a second time. Any idea why it's not working?
Edit jsFiddle here: http://jsfiddle.net/g6PLu/
That's a named function literal.
The name is only visible within the scope of the function.
Therefore, truncate doesn't exist outside of the handler.
Instead, create a normal function and pass it to each():
function truncate() { ...}
$('div').each(truncate);
What's the error message do you get?
You should create function and then call it as per requirement
Define the function
function truncate(){
$('div').each(function(){
});
}
Then call the function
truncate();
Another approach is to establish, then trigger, a custom event :
$('div').on('truncate', function() {
$(this).......;
}).trigger('truncate');
Then, wherever else you need the same action, trigger the event again.
To truncate all divs :
$('div').trigger('truncate');
Similarly you can truncate just one particular div :
$('div#myDiv').trigger('truncate');
The only prerequisite is that the custom event handler has been attached, so ...
$('p').trigger('truncate');
would do nothing because a truncate handler has not been established for p elements.
I know there's already an accepted answer, but I think the best solution would be a plugin http://jsfiddle.net/g6PLu/13/ It seems to be in the spirit of what the OP wants (to be able to call $('div').truncate). And makes for much cleaner code
(function($) {
$.fn.truncate = function() {
this.addClass('closed').children(":not('.truncate')").hide().slice(0,2).show();
};
$.fn.untruncate = function() {
this.removeClass('closed').children().show();
};
})(jQuery);
$('div').truncate();
$('.truncate').click(function() {
var $parent = $(this).parent();
if ($parent.hasClass('closed')) {
$parent.untruncate();
} else {
$parent.truncate();
}
});

Categories