JavaScript event execute immediately after bind? [duplicate] - javascript

I have a link:
<ul id="titleee" class="gallery">
<li>
Talent
</li>
</ul>
and I am trying to trigger it by using:
$(document).ready(function() {
$('#titleee').find('a').trigger('click');
});
But it doesn't work.
I've also tried: $('#titleee a').trigger('click');
Edit:
I actually need to trigger whatever get's called here <a href="#inline" rel="prettyPhoto">

If you are trying to trigger an event on the anchor, then the code you have will work I recreated your example in jsfiddle with an added eventHandler so you can see that it works:
$(document).on("click", "a", function(){
$(this).text("It works!");
});
$(document).ready(function(){
$("a").trigger("click");
});
Are you trying to cause the user to navigate to a certain point on the webpage by clicking the anchor, or are you trying to trigger events bound to it? Maybe you haven't actually bound the click event successfully to the event?
Also this:
$('#titleee').find('a').trigger('click');
is the equivalent of this:
$('#titleee a').trigger('click');
No need to call find. :)

Sorry, but the event handler is really not needed. What you do need is another element within the tag to click on.
<a id="test1" href="javascript:alert('test1')">TEST1</a>
<a id="test2" href="javascript:alert('test2')"><span>TEST2</span></a>
Jquery:
$('#test1').trigger('click'); // Nothing
$('#test2').find('span').trigger('click'); // Works
$('#test2 span').trigger('click'); // Also Works
This is all about what you are clicking and it is not the tag but the thing within it. Unfortunately, bare text does not seem to be recognised by JQuery, but it is by vanilla javascript:
document.getElementById('test1').click(); // Works!
Or by accessing the jQuery object as an array
$('#test1')[0].click(); // Works too!!!

Since this question is ranked #1 in Google for "triggering a click on an <a> element" and no answer actually mentions how you do that, this is how you do it:
$('#titleee a')[0].click();
Explanation: you trigger a click on the underlying html-element, not the jQuery-object.
You're welcome googlers :)

If you are trying to trigger an event on the anchor, then the code you have will work.
$(document).ready(function() {
$('a#titleee').trigger('click');
});
OR
$(document).ready(function() {
$('#titleee li a[href="#inline"]').click();
});
OR
$(document).ready(function() {
$('ul#titleee li a[href="#inline"]').click();
});

With the code you provided, you cannot expect anything to happen. I second #mashappslabs : first add an event handler :
$("selector").click(function() {
console.log("element was clicked"); // or alert("click");
});
then trigger your event :
$("selector").click(); //or
$("selector").trigger("click");
and you should see the message in your console.

Well you have to setup the click event first then you can trigger it and see what happens:
//good habits first let's cache our selector
var $myLink = $('#titleee').find('a');
$myLink.click(function (evt) {
evt.preventDefault();
alert($(this).attr('href'));
});
// now the manual trigger
$myLink.trigger('click');

This is the demo how to trigger event
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input").select(function(){
$("input").after(" Text marked!");
});
$("button").click(function(){
$("input").trigger("select");
});
});
</script>
</head>
<body>
<input type="text" value="Hello World"><br><br>
<button>Trigger the select event for the input field</button>
</body>
</html>

This doesn't exactly answer your question, but will get you the same result with less headache.
I always have my click events call methods that contain all the logic I would like to execute. So that I can just call the method directly if I want to perform the action without an actual click.

For links this should work:
eval($(selector).attr('href'));

You should call the element's native .click() method or use the createEvent API.
For more info, please visit: https://learn.jquery.com/events/triggering-event-handlers/

We can do it in many ways...
CASE - 1
We can use trigger like this : $("#myID").trigger("click");
CASE - 2
We can use click() function like this : $("#myID").click();
CASE - 3
If we want to write function on programmatically click then..
$("#myID").click(function() {
console.log("Clicked");
// Do here whatever you want
});
CASE - 4
// Triggering a native browser event using the simulate plugin
$("#myID").simulate( "click" );
Also you can refer this : https://learn.jquery.com/events/triggering-event-handlers/

Shortest answer:
$('#titlee a').click();

Related

Jquery mouse enter and mouse leave not working on li element

I am trying to use jquery mouse enter and mouse leave functions .
this is my code :
html :
<ul class="menuList bold">
<li id="tevee">
<span>test</span>
</li>
</ul>
jquery
$(function(){
$(".tevee").on("mouseenter",".menuList",hoverInFunction());
$(".tevee").mouseleave(hoverOutFunction("tevee"));
});
function hoverInFunction()
{
alert("hi")
}
function hoverOutFunction(variable)
{
alert("test");
}
https://jsfiddle.net/tejareddy/dndvsudh/ . this is my fiddle , they are not working instead they are triggering on page load and not every time when i hover on them .
Remove the ()
change
$(function(){
$("#tevee").on("mouseenter",".menuList",hoverInFunction());
});
to:
$(function(){
$("#tevee").on("mouseenter",".menuList",hoverInFunction)
});
or do it like this:
$("#tevee").on("mouseenter",".menuList",function(){
alert("hi")
}).on("mouseleave",".menuList", function(){
alert("test");
});
Firstly, your selector was incorrect for the ".on" call, secondly, you were using parenthesis when referring to a function (which in this case must be referred to as an object without the parenthesis).
$(function(){
$(".menuList").on("mouseenter","li",hoverInFunction);
$(".menuList").on("mouseleave","li",hoverOutFunction);
})
Please see the fixed version here
You may use event.data if you wish to pass parameters into the calls.
The original method of binding the event to the ID is not what .on is all about, it's best to bind to a higher-level object in the DOM (such as the actual menuList) and then write a selector which will affect the children on it. That way you get "delegated eventing" and any dynamically added items will still work the way you want them to.

I have to click twice to activate function using jQuery

I am having a lot of trouble with jQuery. I have to click twice on a button to make the page disappear. I have tried importing both versions of jQuery and I tried to use the fadeOut() function on different elements, but nothing has prevailed. It works the second time I click, but never the first. This is a recurring problem, and I need to know how it can be fixed. Here is my code:
HTML:
<body>
<h1>CSS3 Buttons Showcase</h1>
Click Me!
</body>
JavaScript:
function fadeBg(){
$("#btn-1").click(function(){
$("body").fadeOut(1000);
})
}
You must change your function to:
function fadeBg(){
$("body").fadeOut(1000);
}
In your HTML code onclick is being set to run your function fadeBg. So in your function you must put what you want to run; in this case $("body").fadeOut(1000);
The issue is that you're not binding the jQuery event handler until the fadeBg() function is called on the first click. Try this instead:
<h1>CSS3 Buttons Showcase</h1>
Click Me!
$(function() {
$("#btn-1").click(function(){
$("body").fadeOut(1000);
})
});
There are two ways to bind a click to an element :
1. The old dirty inline javascript (avoid)
(HTML) : <button onclick="doSomething()">
and 2. the cleaner event binding
(HTML) : <button id="myButton">
(JS) : $('#myButton').click( doSometing )
You mixed both, binding two clicks on the same element.
<button onclick="doSomething()">
function doSomething(){ // will be done on first click
$('#myButton').click( doSometingElse ) // will be done on second click
}
You are doing the same action twice, the code is:
HTML
<body>
<h1>CSS3 Buttons Showcase</h1>
Click Me!
</body>
JavaScript
$(document).ready(function() {
$("#btn-1").click(function(){
$("body").fadeOut(1000);
})
}
function fadeBg(){
$("#btn-1").click(function(){
$("body").fadeOut(1000);
})
}
You added the onclick event directly in your html. This function adds a second event to the same button.
Just remove the onclick event in your element And do this:
$("#btn-1").click(function(){
$("body").fadeOut(1000);
})
It's considered bad practice adding onclick events directly in your html element. You can but it doesn't look good.

jQuery - trigger a custom event on a link

I am trying to run this custom 'getOffer()' event using jQuery
<img src="images/img.jpeg">
I have tried the following but it doesn't seem to work (I am using the Firefox Firebug console.log window)
$('a[title="Submit for offer"]').trigger('getOffer');
This is the page I am trying this on: http://bit.ly/1dpIMFk
Can anyone suggest any ideas?
<img src="images/img.jpeg">
$(document).ready(function(){
$('a[title="Submit for offer"]').trigger('getOffer');
});
function getOffer(){
alert('link clicked');
}
Seems working fine for me.I think you didnt wrapped your event trigger in document ready.
DEMO
You can use
<img src="images/img.jpeg">
Creating an custom event on jQuery
First add some identifier (id/class) to your link
<a id="linkOffer" title="Submit for offer"><img src="images/img.jpeg"></a>
Then, create your CUSTOM event.
//The function that will to the getOffer things
function getOffer() {
//Do get offer...
}
$(document).ready(function(){
//Custom event pointing to the function
$('a#linkOffer').on('getoffer',getOffer);
//Default click event
$('a#linkOffer').on('click',function(e){
//Do click stuff.
//Trigger your custom event.
$(this).trigger('getoffer');
//If you wish to not move the page, prevent the default link click behavior (moveing to other page)
e.preventDefault();
});
});
Trigger will not function because it search click attribute in element. Work around for this can be is:
Add click attribute to the element and then call the jquery function.
<button value="yu" onclick="getOffer();"/>
<script>
$("a[title='Submit for offer']").attr("onclick",$("a[title='Submit for offer']").attr('href')); // get value from href
$("a[title='Submit for offer']").trigger('click');
function getOffer()
{
alert('j');
}
</script>

Basic jQuery Issues on IE9 (Toggle)

I'm not really a developper. I prefer to design my websites ... So, for my actual project, i must developping some "basic" scripts.
I've met a problem with this:
<script type="text/javascript">
$("button").click(function toggleDiv(divId) {
$("#"+divId).toggle();
});
;
</script>
Into Head-/Head
LINK
<div> id="myContent">Lorem Ipsum</div>
It works for IE8. (Miracle). But not the others browsers...
The idea is that when u click on "LINK" a windows appears and when you click again, the window close.
Any idea ?
Thanks for u time !
One of the problems is you're mixing two different styles of binding event handlers: one of them is good (the jQuery method), the other is bad (the javascript: protocol in your href attribute) - the two don't work together in any way. Another problem is that your selector is completely incorrect (it's looking for a button) for the HTML you've provided (you never create a button).
I'd suggest using a HTML5 data-* attribute to specify the id for the <div> on your <a> element:
LINK
<div id="mycontent">Lorem ipsum</div>
Then use the following jQuery code:
$('a').click(function(e) {
e.preventDefault(); // e refers to the event (the click),
// calling preventDefault() will stop you following the link
var divId = $(this).data('divid');
$('#' + divId).toggle();
});
Note that I've used this in the above code; what this refers to depends on the context in which you use it, but in the context of a jQuery event handler callback function, it will always refer to the element that triggered the event (in this case, your <a> element).
If you extract toggleDiv from the handler, it ought to work. You will probably also need to return false to keep the href from trying to go anywhere.
<script type="text/javascript">
function toggleDiv(divId) {
$("#"+divId).toggle();
return false;
}
</script>

jQuery on(click) doesn't work but on(hover) does

After initialize js I create new <div> element with close class and on("click") function doesn't work.
$(document).on('click', '.post-close', function () {
alert("hello");
});
but on('hover') work perfectly.
$(document).on('hover', '.post-close', function () {
alert("hello");
});
but I need to make it work on click.
It's because you're not preventing the default behaviour of the browser. Pass e into your handler and then use e.preventDefault()
$(document).on('click', '.post-close', function (e) {
e.preventDefault();
alert("hello");
});
Edit
Also, bind the handler before creating the new <div>
why not use something like
$('.post-close').click(function(){
//do something
});
If the element was added dynamically use:
$(document).on('click', '.post-close', function(){
//do something
});
edit:
like danWellman said, you can add the preventDefault IF you want to make sure no other code is executed. otherwise use the code above.
edit2:
changed the .live to .on
It's an old post but I've had a exactly same problem (element created dynamically, hover works, but click doesn't) and found solution.
I hope this post helps someone.
In my case, I found ui-selectable is used for parent element and that was preventing from click event propagate to the document.
So I added a selector of the button element to ui-selectable's 'cancel' option and problem solved.
If you have a similar probrem, check this
Try turn of libraries for parent element
You're not using stopPropagation() in parent element ?

Categories