I have something like this im my project:
<input onchange="doSomething();" .... />
<a href="url" ... ></a>
If input field is focused and I click 'a' link, the browser goes to URL and the event onchange fires only after that. But I want at first to run function "doSomething()" and only then go to the url. How to solve it better?
remove the inline javascript and use jQuery. Preferably you would add some ID's or classes to those elements to target them.
$('input').on('change', doSomething);
$('a').on('click', function(e) {
e.preventDefault();
doSomething();
document.location.href = this.href;
});
Assuming doSomething() is not asynchronous, as that would be completely different.
You could do something like this with jQuery (Not tested)
..
$('a').click(function(){
dosomething();
$(this).attr('href', 'url');
});
instead of onchange event, use onblur at Input.
<input onblur="doSomething();" type="text" />
Hello
Test the demo from http://jsfiddle.net/Bhaarat/V3wT9
if requirement can be satisfied with javascript only then why to create overhead of jquery ?
Please let me know reason for downvote
Related
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();
I want hash-tags to be removed from URL after they are used.
For example, when i click on the link below:
<button type="button" name="" value="" id="btnq1">Just a button</button>
I want the hash-tag #btnq1 that appears to the URL of the page to be removed just after the action on this link happens.
I tried the below jquery code with no success:
$('#btnq1').click(function(event){
event.preventDefault();
// your action
});
And even if this works, then how do i implement it to work for every hash tag that is added to the URL?
I would like to solve it using javascript.
You could try that:
$(window).on('hashchange', function(e){
history.replaceState ("", document.title, e.originalEvent.oldURL);
});
first add a class to your a tag that you want this behavior for, or a html 5 data- attribute. Then your link becomes;
<button>Button</button>
$('body').on('click', ".remove-hash", function(e){
$(this).removeAttr('href');
});
Hi am developing a webpart which is included in sharepoint app and I need to stop redirection in some cases. But it doesn't work, i am trying to use
$('a').click(function(event){
event.preventDefault();
event.stopImmediatePropagation();
return false;
});
it executes and anyway redirection is done. How can I break it?
Purpose of it is: when user change sth on page I need to ask if he wants to proceed or not and then stop any redirection from othe links he might clicked.
Edit:
I just checked and with regular a with links inside it works but the problem is with link like this:
<a title="Delivery And Technology" class="ms-cui-ctl-large" id="someId" role="button" onclick="return false;" href="javascript:;" unselectable="on" mscui:controltype="" jQuery182001210093900916337="93">
which has inside this html
<SPAN class=ms-cui-ctl-largeIconContainer unselectable="on"><SPAN class=" ms-cui-img-32by32 ms-cui-img-cont-float ms-cui-imageDisabled" unselectable="on"><IMG style="TOP: -96px; LEFT: -160px" alt="Delivery And Technology" src="/_layouts/1033/images/ps32x32.png" unselectable="on"></SPAN></SPAN><SPAN class=ms-cui-ctl-largelabel unselectable="on">Delivery And<BR>Technology</SPAN>
so seems that when I click on this java script recognize it and redirects me so what i want to achive is to detect it and stop before it will redirect me to other page.
This will prevent dynamically added anchors from navigating too:
$(document).on('click', 'a', function(e){
e.preventDefault();
e.stopImmediatePropagation();
return false;
});
steveukx suggested shorthand:
$(document).on('click', 'a', false);
My best guess is that you run this code before the DOM is ready. Try wrap it in a DOM-ready callback:
$(function () {
$('a').click(function(event){
return false;
});
});
Note that returning false is equivalent to .preventDefault() and .stopImmediatePropagation() together, so just returning false will be sufficient. In your case it might be more appropriate to just use .preventDefault() and nothing else though.
If the element has a had a handler attached before your code executes, it isn't possible to reliably remove or prevent the handler from running.
Assuming you have jQuery available, and you are running this function after the element has been added to the DOM and had its handlers attached you can replace it with an identical element:
jQuery('a').replaceWith(function(index, innerHTML) {
return jQuery(this.cloneNode(false)).html(innerHTML);
});
For a page, I've been given a link wrapped inside a label, like this:
<label for='checkbox_elem'>
Links to <a href='somepage.php' target='anotherwindow'>another page.</a>
</label>
When the user clicks on the link in all browser, the page is spawned in a new tab as envisioned, but in Firefox the checkbox linked to the label is also selected. This is a non-desired behavior.
I want to run some jQuery to allow the link to pop, but to kill the event thereafter. I have the following, which works, but isn't very elegant:
$(document).ready(function(){
$('label a').click(function(e){
open($(this).attr('href'), $(this).attr('target'));
return false;
});
});
Can any of you think of a more elegant way to do this than to replicate the element's behavior manually and kill the event?
As an aside, I've been trying with stopPropagation, but haven't had much success.
Also, please note that the above solution does work, but I am looking for something more elegant for generically stopping events from propagating past their first call. (The first native call. If I add a callback, I still want the native element behavior to fire, but not that of its parent) .
Try stopping the event from propagating at the label.
$(document).ready(function(){
$('label').click(function(e){
e.stopPropagation();
});
});
You could use $(elem).one(fn) -- http://api.jquery.com/one/
Maybe you should change your html to:
<label for='checkbox_elem'>Links to </label>
<a href='somepage.php' target='anotherwindow'>another page.</a>
and use no javascript at all?
This one:
<label> test Test <input type="checkbox" name="check[]" /></label>
Or even:
<label for="test1"> test Test <input type="checkbox" name="test1" id="test1" class="checkbox" /></label>
And js:
$('a').click(function(e){
var t=$(this);
window.open(t.attr('href'), t.attr('target'));
return false;
});
Works for me. Maybe there is smth that interfere with your script?
Well, if you are allowed to change the html on client-side, you can always move the links outside the label like this,
$(document).ready(function(){
$('label').find('a').each(function(){
var $anchor = $(this);
$(this).closest('label').after($anchor);
});
});
demo
KISS
$(document).ready(function(){
$('label a').click(function(e){
open($(this).attr('href'), $(this).attr('target'));
$(this).parent().click(); //Click the label again to reverse the effects of the first click.
return false;
});
});
Try using .one() instead of .click():
$(document).ready(function(){
$('label a').one(function(e){
open($(this).attr('href'), $(this).attr('target'));
return false;
});
});
I am dynamically creating a hyperlink in the c# code behind file of ASP.NET. I need to call a JavaScript function on client click. how do i accomplish this?
Neater still, instead of the typical href="#" or href="javascript:void" or href="whatever", I think this makes much more sense:
var el = document.getElementById('foo');
el.onclick = showFoo;
function showFoo() {
alert('I am foo!');
return false;
}
Show me some foo
If Javascript fails, there is some feedback. Furthermore, erratic behavior (page jumping in the case of href="#", visiting the same page in the case of href="") is eliminated.
The simplest answer of all is...
My link
Or to answer the question of calling a javascript function:
<script type="text/javascript">
function myFunction(myMessage) {
alert(myMessage);
}
</script>
My link
With the onclick parameter...
<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>
The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:
<div class="menu">
Example
Foobar.com
</div>
<script>
jQuery( 'div.menu a' )
.click(function() {
do_the_click( this.href );
return false;
});
// play the funky music white boy
function do_the_click( url )
{
alert( url );
}
</script>
I prefer using the onclick method rather than the href for javascript hyperlinks. And always use alerts to determine what value do you have.
<a href='#' onclick='jsFunction();alert('it works!');'>Link</a>
It could be also used on input tags eg.
<input type='button' value='Submit' onclick='jsFunction();alert('it works!');'>
Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.
Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:
[c# example only probably not the way you're writing out your js]
Response.Write("My Link");
[Javascript]
document.getElementById('uxAncMyLink').onclick = function(e){
// do some stuff here
return false;
}
That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.
Hope that is of use.
Use the onclick HTML attribute.
The onclick event handler captures a
click event from the users’ mouse
button on the element to which the
onclick attribute is applied. This
action usually results in a call to a
script method such as a JavaScript
function [...]
I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.
attachEvent / addEventListening allow multiple event handlers to be created.
If you do not wait for the page to be loaded you will not be able to select the element by id. This solution should work for anyone having trouble getting the code to execute
<script type="text/javascript">
window.onload = function() {
document.getElementById("delete").onclick = function() {myFunction()};
function myFunction() {
//your code goes here
alert('Alert message here');
}
};
</script>
<a href='#' id='delete'>Delete Document</a>