Trigger click function on load - javascript

I have the following function which is activated on click:
$('.results .view-rooms').click(function(){ }
Is there anyway I can trigger this function on document load?

Yes.
$(document).ready(function(){ // on document ready
$(".results .view-rooms").click(); // click the element
})

$('.results .view-rooms').click()
You can put it in DOM ready:
$(function(){
$('.results .view-rooms').click()
});
Or window load:
$(window).load(function(){
$('.results .view-rooms').click();
});
Note that there is no such event document load.
We have DOM ready or window load

$(document).ready(function(){ $('.results .view-rooms').click(); });

Considering that you're already using jQuery to bind the event handler, and assuming that code is already in a position where the entire DOM has been constructed, you can just chain the call to .click() to then trigger that event handler:
$('.results .view-rooms')
.click(function(){...}) //binds the event handler
.click(); // triggers the event handler

Put the code inside
$(function(){ // code here });
like:
$(function(){
$(".results .view-rooms").click();
});
or
$(function(){
$(".results .view-rooms").trigger('click');
});

$(function(){
$('.results .view-rooms').click(function(){
}
$(".results .view-rooms").trigger('click');
}

The best way is:
html form:
<form action="https://stackoverflow.com" method="get">
<button id="watchButton"></button>
</form>
End Jquery:
<script>
$('document').ready(function() {
$('#watchButton').click();
});
</script>
JQuery Version:
https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js

Related

dynamically added anchor click doesn't call function in jquery mobile

My page fetches string data from local SQL and appends it to data-role='listview' as li using function below(simplified version)
function CreateListview{
var temp ='<li>String Here</li>';
$("#<ul>-selector").append(temp).listview("refresh");
}
well, it works fine so I binded a click event for the anchor(class='.anchor')
$(document).on('vclick', '.anchor', function(e){
e.preventDefault();
alert("ANCHOR CLICKED");
});
OR
$(document).on('vclick', '#ul-selector > a', function(e){
e.preventDefault();
alert("ANCHOR CLICKED");
});
OR
$(document).on('vclick', '#ul-selector > li a', function(e){
e.preventDefault();
alert("ANCHOR CLICKED");
});
OR even
$(document).on('vclick', 'a', function(e){
e.preventDefault();
alert("ANCHOR CLICKED");
});
But nothing works
I double-checked if click event on other elements works by using the function below on dynamically added li and it sometimes works and sometime doesn't.
I don't know why it works randomly,
but I checked that click events are fired on some other dynamically added elements.
$(document).on('vclick', '#ul-selector > li', function(e){
alert("<li> CLICKED");
});
When it comes to binding click function to dynamically added anchors, the function won't be fired..
could it be a bug? or am I writing codes wrong?
Can you give me a working example binding click event to dynamically added anchor?
It seems works fine for me.
function CreateListView() {
var temp ='<li>String Here</li>';
$("#selector").append(temp).listview("refresh");
}
$(document).on('vclick', '.anchor', function(e){
e.preventDefault();
alert("ANCHOR CLICKED");
});
$("#createLi").on("vclick", function(){
CreateListView();
alert("test");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
<div id="content">
<ul id="selector">
</ul>
</div>
<input id="createLi" type="button" value="create li"/>
Am I missing something?
You're not listening to the click event but vclick(???).
$("yourUl").on('click', '.anchor', function(e){
e.preventDefault();
alert("ANCHOR CLICKED");
});
bind the event after you append the html like this
function CreateListview{
var temp ='<li>String Here</li>';
$("#<ul>-selector").append(temp).listview("refresh");
$("#<ul>-selector > li").on("click",function(){
alert("<li> CLICKED");
});
}
check this fiddle you can apply the same logic here
I found the solution.
Problem: with cordova, 'click' on anchor doesn't fire function even with e.preventDefault(); Rather, 'touchstart' works fine.
Solution: 'click' -> 'touchstart' to work on devices
$(document).on('touchstart', '#anchor-selector', function(){
alert("touch");
});

Using :not() to ignore clicks on children links?

In a script I'm writing with JQuery I'm trying to add a click handler to a div, but ignoring clicks on the children a tags inside it.
You can see a JSFiddle of how I'm currently trying (and failing) to make it happen here: http://jsfiddle.net/q15s25Lx/1/
$(document).ready(function() {
$(document).on('click', '.post:not(a)', function(e) {
alert($(this).text());
});
});
<div class="post">This is some text in a div. Click me please.</div>
In my real page, the a tags all have their own click handlers, so I need to be able to listen for those concurrently.
So, ideally I'd like to use something like the :not() selector to ignore clicks on this particular handler.
Is something like this possible?
You'll need to add another handler that acts on the anchor and stops the event from propagating:
$(document).on('click', '.post a', function (e) {
e.stopPropagation();
e.preventDefault();
});
Without this, when you click the a the event bubbles up to the parent .post, and the handler fires on that anyway.
You need to stop event propagation to child elements using .stopPropagation():
$(document).on('click', '.post a', function(e) {
e.stopPropagation();
});
Working Demo
Just return false; in the end of event handler.
$(document).on('click', '.post', function (e) {
alert($(this).text());//will show entire text
});
$(document).on('click', '.post a', function (e) {
alert($(this).text());//will show 'text'
return false;
});
working fiddle: http://jsfiddle.net/q15s25Lx/2/
return false will server as both e.preventDefault() &
e.stopPropagation()
Try to stop the event from bubbling up the DOM tree using stopPropogation()
$(document).ready(function() {
$(document).on('click', '.post a', function(e) {
e.stopPropagation();
alert($(this).text());
});
});
Fiddle Demo
All of the other posts did not explain why your code failed. Your selector is saying : Find an element that has the class post and is not an anchor. It is NOT saying if a child was clicked and was an achor do not process.
Now there are two ways to solve it. One is to prevent the click from bubbling up from the anchors. You would add another listener on the anchors.
$(document).on('click', '.post a', function (evt) {
evt.stopPropagation(); //event will not travel up to the parent
});
$(document).on('click', '.post', function (evt) {
console.log("Click click");
});
Or the other option is not to add a second event, but check what was clicked.
$(document).on('click', '.post', function (evt) {
var target = $(evt.target); //get what was clicked on
if (target.is("a")) { //check to see if it is an anchor
return; // I am an anchor so I am exiting early
}
console.log("Click click");
});
Or jsut let jquery handle it all for you. return false
$(document).on('click', '.post:not(a)', function() {
alert($(this).text());
return false;
});

Why my click not work as expected?

I just try this code:
$("#test").ready(function() {
$(this).click(function() {
alert('clicked!');
});
});
Fiddle here: http://jsfiddle.net/8bfqw/
Why it's still alert when I click outside of the div?
It's because your selector $(#test) is actually $(document) since from the docs:
The .ready() method can only be called on a jQuery object matching the
current document
Whatever you pass inside the selector, it'll be omitted and work on the current document. A shorthand version of $(document).ready(function(){}) is $(function(){}); so you want:
$(function() {
$('#test').click(function() {
alert('clicked!');
});
});
$("#test").ready(function() {
$("#test").click(function() {
alert('clicked!');
});
});
$("#test").ready(function() {
$("#test").click(function() {
alert('clicked!');
});
});
You have to set the click-function to the Test-object, instead of the whole document $(this).

How to attach event to the newly added anchor using jquery

I trying to attach a click event for the newly added anchor tag(.he) after the #foo anchor tag. But the click event is not happening. I have used (.on). Can you guys help me in this ?*
<!DOCTYPE html>
<html>
<head>
<title>Attaching event</title>
<style>p { background:yellow; margin:6px 0; }</style>
<script src="js/jquery.js"></script>
</head>
<body>
<p>Hello</p>
how are
<p>you?</p>
<button>Call remove() on paragraphs</button>
<a id="foo" href="#" style="display:block">Testing the bind and unbind</a>
<script>
$("button").on('click',function () {
$("#foo").after("<a class='he' href='#'>asdfasdf</a>");
});
$(".he").on('click', function(){
alert("test");
});
</script>
</body>
You have to delegate to a static parent element like this
$(document).on('click','.he',function(){
//code here
});
Use event delegation
$("body").on("click", ".he", function() {
alert("test");
});
Instead of body you can use any static parent element of .he.
use .live. and don't forget to add your code inner jquery clousure
<script>
$(function(){
$("button").on('click',function () {
$("#foo").after("<a class='he' href='#'>asdfasdf</a>");
});
$(".he").live('click', function(){
alert("test");
});
});
<script>
you will have to put the below code inside $("button").click block.
$(".he").on('click', function(){
alert("test");
});
Link for jsfiddle http://jsfiddle.net/wbWLE/
You can instead bind the click event to the anchor before appending it to the DOM like this:
var $he = $("<a class='he' href='#'>asdfasdf</a>").on('click', function(){
alert("test");
})
$("#foo").after($he);
You can either attach a handler to the anchor directly before it is appended into the document:
$("button").on('click',function () {
$("<a class='he' href='#'>asdfasdf</a>")
.on('click', function(){
alert("test");
})
.insertAfter("#foo");
});
or bind a delegate handler on the document that will catch all clicks on anchors with he as their class:
$(document).on('click', 'a.he', function() {
alert("test");
});
$("button").on('click',function () {
$("<a class='he' href='#'>asdfasdf</a>").insertAfter("#foo");
});

How to bind click events to a different class?

So I have two click events for "button-open" and "button-close". I have one button that switches from "button-open" to "button-close" on click. So when i click it again, it should fire the event for "button-close" but instead it fires the event for "button-open" again.
Demo : jsFidde
Here's my code:
Button​
<script>
$(document).ready(function() {
$(".button-open").click(function() {
$(this).removeClass("button-open").addClass("button-close");
alert("Open Was Clicked");
});
$(".button-close").click(function() {
$(this).removeClass("button-close").addClass("button-open");
alert("Close Was Clicked");
});
});
</script>
Use on() instead of click(), since you need to bind to an element that doesn't yet exist when you initially bind it.
$(document).on('click', '.button-open', function() {
$(this).removeClass("button-open").addClass("button-close");
alert("Open Was Clicked");
});
$(document).on('click', '.button-close', function() {
$(this).removeClass("button-close").addClass("button-open");
alert("Close Was Clicked");
});
DEMO.

Categories

Resources