How do you override inline onclick event? - javascript

This seems deceptively simple.
How do you override the onclick event in the following HTML using JavaScript?
<a id="sample" href="..." onclick="alert('hello world')" />...</a>
I've tried it with jQuery, but that didn't do the trick:
$('#sample').attr('onclick','alert("done")')
Assume the HTML is pre-written and cannot be changed, other than manipulating it with JavaScript.

Try this:
// Setting the DOM element's onclick to null removes
// the inline click handler
$("#sample")[0].onclick = null;
$("#sample").click(function() { alert("done") });

This can also be done without jQuery:
document.getElementById("sample").setAttribute('onclick','alert("done")');

<a id="sample" href="..." onclick="alert('hello world'); return false;" />...</a>
Or
$('#sample').attr('onclick','alert("done"); return false;')
Despite being able to set the return false; either directly in the onclick or by using jQuery, it doesn't actually require jQuery to be used at all. The benefit is if for whatever reason your jQuery script leads to a 404, your code will still work.
I found the answer here.

Try:
document.getElementById("sample").onclick = $.noop;
$.noop == function(){};
jQuery noop

Related

How to use functions on href (html/js)

want to build a function inside a href link.
should look like this
How do i complete it correct?
Use onclick to trigger a function instead of href
HTML
JS
function destroy()
{ //rest of the code
return false; // return false is use to prevent default behavior
}
Note: If you dont use return false or event.preventDefault it will execute the default behavior
There are different option for you to use.
Most of them already answered in another question.
Sum it up:
You can do it like this (the correct way):
<a id="myLink" title="Click to do something" href="PleaseEnableJavascript.html" onclick="destroy();return false;">link text</a>
What it means is that after the destroy function is called it wont direct the user to the link provided. Alternatively you can use jQuery to make a listener on the specific a href like this:
$('#myLink').click(function(){
MyFunction();
return false;
});
The rest can be read on the provided link :)

.replace in JavaScript/jQuery

I am using .replace method to replace onclick function on anchor tag but it is not working.
<script type="text/javascript">
$(function(){
var htm= $('.jitu').html();
htm.replace("show()",'showme()');
})
</script>
<div class="jitu">me </div>
You should use :-
$('.jitu a').attr('onclick','showme()');
http://jsfiddle.net/Fxfvn/
Explanation on your code:-
What you are doing is just replacing a string not the real DOM. ALso this is not an ideal way to change an attribute. here html is just an html string and no reference...
var htm= $('.jitu').html();
htm.replace("show()",'showme()');
Since you are using jquery. You can directly bind
$('.jitu a').removeAttr('onclick').click(showme); //(if you have onclick. to avoid duplicate alert)
else
$('.jitu a').click(showme);
Use the .attr( attributeName, value ) function instead.
Another approach:
$('.jitu').find('[onclick="show()"]').attr('onclick', 'showme()');
http://jsfiddle.net/CfpBP/
However you should consider using more unobtrusive way to bind events. For example:
$('.jitu a').click(showme);
Just doing a string replacement doesn't do anything if you're not applying the final value to the element; this would work but I would not recommend it:
var $jitu = $('.jitu');
$jitu.html($jitu.html().replace('show()', 'showme()'));
The more correct way is to unhook the old onclick and replace it with a new click handler:
$('.jitu > a')
.prop('onclick', null)
.on('click', showme);
Demo
It would be even better if you didn't even have the inline onclick="show()" in the first place and just use $(element).on(event, fn) to register your click handlers.
This should do the trick:
htm.onclick = function() { showme(); };

Jquery onclick event

I have a link
<a id="special_link" href="" onclick="" >Link</a>
Is it possible to use Jquery in the onclick part and apply something to the current element?
Something similar with :
$("#special_link").html('test');
Update :
I want to change the content after click
I would prefer using $this so I don't depend on the id
Yes, it's possible:
<a href='whatever' onclick='$("#special_link").html("test");'>blah</a>
It's rarely necessary, though. Usually you can hook these things up later, using a selector that finds the a element and uses bind or click to hook up a handler, e.g.:
jQuery(function($) { // Function gets run at DOM load time
$("some_CSS_selector_that_finds_the_a_element").click(function() {
$("#special_link").html("test");
return false; // Do this only if you don't want the link followed (which I'm guessing you don't)
});
});
If special_link is the id of the link you want to do this on (I wasn't sure, from your question), you can simplify that:
jQuery(function($) { // Function gets run at DOM load time
$("#special_link").click(function() {
$(this).html("test");
return false; // Do this only if you don't want the link followed (which I'm guessing you don't)
});
});
More:
bind
click
$
The code you provided will work as-is in the onclick attribute, like T.J. Crowder pointed out. Is your problem using jQuery for the current element? like this:
<a href='#' onclick='$(this).html("a test link");'>a link</a>
You can refer to the current element as this.
Example:
<script ...>
$("#special_link").click(function() {
console.log(this) // You'll see the HTML element, not wrapped by jQuery
$(this).html("Bar");
})
</script>
Foo
Please, don't use onclick, rely on bind that's more generic and unobstructive.
Good luck!
If you want it inline, and it's as simple as changing the HTML, I probably wouldn't use jQuery for it.
<a id="special_link" href="#" onclick='this.innerHTML="some new value";'>click me</a>
Example: http://jsfiddle.net/8ucGB/2/

how do we change onclick function via .attr() in jquery?

i got this url
<a class="remove_item' rel="4" onclick="javascript:jQuery(#blablabla)" href="javascript:;' >remove</a>
i'm using this simple find and replace
item.find('a.remove_class').attr({
title:'hello',
click:'hello();'
} );
but it seem it's not working. i still not able to replace javascript:jQuery(#blablabla) with another function.
To set onClick you should use something like this $("a").attr("onclick", js);
where js is a string containing your javascript code.
Try attaching the event handler using the below code snippet in your page body:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('.remove_item').click(hello);
});
</script>
jQuery has no built-in way to assign event handlers in that way. Use the DOM0 method to set the onclick handler instead:
item.find('a.remove_class').each(function() {
this.onclick = function() {
alert("Clicked!");
};
});
Also, don't put javascript: in you event handler attributes. It's incorrect and only works by coincidence.
Why not just do this.
<script type="text/javascript">
$(document).ready(function() {
$("a.remove_item").click(function() {
alert("You have clicked my <a>!!");
//do other stuff
});
});
</script>
The attr doesn't recognises the onclick attribute, get the html element (.get(0)) and use "raw" functions to extract the onclick attribute.
On Firefox the following works:
$("element").get(0).getAttribute("onclick")
You can remove by using
$("element").get(0).removeAttribute("onclick")
or setting a empty string
$("element").get(0).setAttribute("onclick", "")

referencing (this) in a function

I have elements being generated by dynamic html, I would like to reference the particular href that is calling the function when one of many may be calling it.
Link
Does not work when I try to reference $(this). Is there another way to do this or do I have to make dynamic ids?
Link will work if you want to pass the href.
However, onsomething handlers in the html code are not jqueryish at all.
Give your links a class and setup a live handler:
$('.mylink').live('click', function() {
// do whatever you want with this or $(this) or this.href or $(this).attr('href')
});
putting the js parts in the href attribute is a bad idea. best practice is adding a handler with addEventListener but here you can get away with setting onclick directly.
Link
and your function would be like
function Foo(e) {
var a = e.target || e.srcElement;
// TODO: stuff
if (e.preventDefault) {
e.preventDefault();
}
else {
return false;
}
}
so when you click the link, Foo is called with the event as a paremeter. the event object has a reference to the source element, either as target in standards browsers or srcElement in IE. the preventDefault/return false; combo at the end prevents the browser from "following" the link to #.
edit: on second thought, since you have many links, using jquery to add handlers the recommended way is probably better (although the first solution is still fine).
...
<a id="A5" href="#" >Link</a>
<a id="A6" href="#" >Link</a>
<a id="A7" href="#" >Link</a>
...
<script>
$('a').click(Foo);
</script>
No point in using the javascript: pseudo protocol handler.
Use
Link
instead.

Categories

Resources