Apply A Function to All Links on Page - javascript

i have my all links on page like this :
Example
But Now I Want All Links With Following OnClick Function like this:
<a onclick="show();" href="http://example.com">Example</a>
can any one tell me jquery or javascript code to add above function to all links on body, thanks

Some answers have suggested to use jQuery's click() function. That's alright as long as you don't expect to add new links dynamically using javascript.
This click handler will bind on the <body> element, and fire whenever a <a> element inside it is clicked. The advantage with this over $('a').click(...) is that all <a> tags don't need to be present on page load:
$(function () {
$('body').on('click', 'a', function (event) {
event.preventDefault();
show();
});
});
Fiddle: http://jsfiddle.net/Lubf6gjw/2/
EDIT: Here's how to do it with pure javascript:
document.querySelector('body')
.addEventListener('click', function (event) {
if(event.target.tagName === 'A') {
event.preventDefault();
show();
}
});
http://jsfiddle.net/pymwsgke/1/

$(function(){
$("a").click(function(){
show();
}
});
If you want to prevent the browser from following the href, you can just add a preventDefault call
$(function(){
$("a").click(function(e){
e.preventDefault();
show();
}
});
Note that this will not actually append the onclick= to the <a> tags. If you want to do that, you can do it this way:
$("a").each(function(){
$(this).attr("onclick", $(this).attr("onclick")+";show();");
});

Using pure Js
function show (event) {
event.preventDefault();
// do somethink
}
var anchors = document.querySelectorAll("a");
for(var a = 0; a < anchors.length; a++) {
anchors[a].addEventListener("click",show,false)
}

Related

html div onclick event

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint"
onclick="markActiveLink(this);">ABC</a>
</h2>
</div>
js code
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
here I when I click on div I got alert with 123 message, its fine but when I click on ABC I want message I want to call markActiveLink method.
JSFiddle
what is wrong with my code? please help me out.
The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".
In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
$('.expandable-panel-heading').click(function (evt) {
if (evt.target.tagName != "A") {
alert('123');
}
// Also possible if conditions:
// - evt.target.id != "ancherComplaint"
// - !$(evt.target).is("#ancherComplaint")
});
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
Stopping the event propagation from the anchor click listener
→ jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
As you may have noticed, I have removed the following selector part from my examples:
:not(#ancherComplaint)
This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
Try this
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').click(function (event) {
alert($(this).attr("id"));
event.stopPropagation()
})
DEMO
Try following :
$('.expandable-panel-heading').click(function (e) {
if(e.target.nodeName == 'A'){
markActiveLink(e.target)
return;
}else{
alert('123');
}
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
Here is the working demo : http://jsfiddle.net/JVrNc/4/
Change your jQuery code with this. It will alert the id of the a.
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();
alert('123');
});
function markActiveLink(el) {
var el = $('a').attr("id")
alert(el);
}
Demo
You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway
Test the click on the div and examine the target
Live Demo
$(".expandable-panel-heading").on("click",function (e) {
if (e.target.id =="ancherComplaint") { // or test the tag
e.preventDefault(); // or e.stopPropagation()
markActiveLink(e.target);
}
else alert('123');
});
function markActiveLink(el) {
alert(el.id);
}
I would have used stopPropagation like this:
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').on('click',function(e){
e.stopPropagation();
alert('hiiiiiiiiii');
});
Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>
http://jsfiddle.net/NXML7/1/
put your jquery function inside ready function for call click event:
$(document).ready(function() {
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
});
when click on div alert key
$(document).delegate(".searchbtn", "click", function() {
var key=$.trim($('#txtkey').val());
alert(key);
});

Add click event to all 'a' tags in main menu

$(document).ready(function () {
$("#MainMenu a").click(function () {
$("#divContent").load( ???? );
});
});
I want to retrieve all links from my main menu, attach click events to them, and tell jQuery to load some content to #divContent via ajax call. Content location should depend ofcourse on href tag in each link.
You are almost there, Try:
$("#MainMenu a").click(function (e) {
e.preventDefault(); //prevent the default click behavior of the anchor.
$("#divContent").load(this.href); //just get the href of the anchor tag and feed it onto load.
});
If you're looking for performance as well and you have a large list of options the best approach would be:
$(document).ready(function () {
$('#MainMenu').on('click', 'a', function (e) {
e.preventDefault();
var $a = $(this);
$("#divContent").load($a.prop('href'));
});
});

jquery click event on element not having a class

How would I make sure that this href element is will fire "click" event unless it does NOT have "disablelink" class.
DO NOT PROCESS:
<a class="iconGear download disablelink" href="#">Download</a>
PROCESS:
<a class="iconGear download" href="#">Download</a>
tried this without success:
$("a.download").not(".disablelink").click(function (e) {
alert('in');
e.preventDefault();
});
This should work:
$("a.download:not('.disablelink')").click(function (e) {
alert('in');
e.preventDefault();
});
If the disablelink class is being added dynamically:
$(document).on('click', "a.download:not('.disablelink')", function (e) {
alert('in');
e.preventDefault();
});
Check this demo: http://jsfiddle.net/d3rXr/1/
$('a.download').click(function(e){
e.preventDefault();
if($(this).hasClass('disablelink')){
return;
}else{
//other stuff;
}
});
Why don't you check when the anchor is clicked, and if it has the class it returns and does nothing, which would be more readable code I guess.
You could go like this:
$("a.download").click(function(e) {
if($(this).hasClass("disablelink")) {
return false;
}
// Normal code
alert('in');
e.preventDefault();
});
Firstly, this probably doesn't work because some links had disablelink added to them dynamically, and after they already had the click handler bound to them.
Secondly, you should just check for that class inside the click handler, like so:
$("a.download").click(function (e) {
if($(this).hasClass('disablelink')){
e.preventDefault();
// link is disabled
}else{
alert('in');
// link is active
}
});

Override javascript click event one time

I would like to replace the default action of an click event for all anchors in a webpage.
When I use this piece of code:
<html> <head> <script>
var list=document.getElementsByTagName("a");
var isChecked = false;
function load () {
for (i=0; i<list.length; i++)
{
var old = (list[i].onclick) ? list[i].onclick : function () {};
list[i].onclick = function () {
if( !isChecked)
{
test();
old();
}
else
old();
};
}
}
function test() {
alert("new action");
isChecked = true;
}
</script> </head>
<body onload="load();">
<a id="nr_1" onClick="alert('test');"> Anchor 1 </A>
<a id="nr_2" onClick="alert('test2');"> Anchor 2 </A>
</body> </html>
When I click an anchor I get the alert out of the test function and then the default function of the second anchor (even when I click the first anchor). When I then again click one of the two anchors I always get the Alert from the second anchor.
How do I put the original onclick functions back for each anchor element? When someone has an solution in jquery I would be glad as well.
EDIT
I was succesfull using this code:
function load()
{
$('a').attr('disabled', 'disabled');
$('a').click(function(e){
if($(this).attr('disabled'))
{
alert("new");
e.preventDefault();
$('a').removeAttr("disabled");
this.click();
}
});
}
On loading of the page this function is called giving all anchor elements a "disabled" attribute. After clicking the element the e.preventDefault() function disables the inline onclick function. Then I remove the "disabled" attribute and call the click function of the element again. because now the element doesn't have a "disabled" attribute only the default function is performed. I'm still open for "more elegant" solutions to this problem, but for now I'm a happy camper!
If you use jQuery you can combine a one-time handler with a persistent handler:
Documentation for .one() and .on()
Working Example: http://jsfiddle.net/Q8gmN/
Sample HTML:
<input type="button" id="click" value="click" />
​
Sample JavaScript:
button.one('click', function () {
console.log('one time function fired');
});
button.on('click', function () {
console.log('persistent function fired');
});
​

Anchor tag jQuery Click

I have an Anchor Tag like this
<a href="javascript:anchorScr()" id="anch1" class ="af-link"/>
It is taking me two clicks on the anchor tag to respond to the javascript function anchorScr();
function anchorScr() {
jQuery('a').click(function (event) {
var id = $(this).attr("id");
alert(id);
});
}
Am I doing something wrong? Why my anchorScr() is not called on the first click ?
This calls the anchorScr function when the anchor is clicked:
href="javascript:anchorScr()"
The function then attaches a click event handler to all a elements.
Remove the href and just have this:
jQuery('a').click(function (event) {
var id = $(this).attr("id");
alert(id);
});
The code will execute - attaching the click event handler to all a elements. You should probably only run this on ready() to ensure that the page has fully loaded into the DOM.
click here
jQuery(document).ready(function(){
jQuery('a').click(function (event) {
var id = $(this).attr("id");
alert(id);
});
});

Categories

Resources