Javascript .on event handler - javascript

I have the following scenario; in my js I have a dynamic hyperlink that I need to capture the clicked link id.
for (var i = 0; i < neighbor.data[3].length; i++){
<a class="Chris" name="a" id="+i+" href="Chris">Hi</a>
}
Now I can get this with;
parseInt($(this).attr("ID"));
I am using this to capture the it;
$(document).on("click", "a.a", function(event) {
event.stopPropagation();
alert(clickedID);
clickedID = parseInt($(this).attr("ID"));
});
Now, my problem is that everytime I click on the hyperlink instead of only one clickedID I have one for every hyperlink clicked. Is there a way to prevent this?

I believe you are getting every anchor tag because you are setting the event on the document, rather than the anchor tag. Try this instead:
$('a').on('click',function(event) {
event.stopPropagation();
clickedID = parseInt($(this).attr('id'));
alert(clickedID);
});

You have an error in your for loop. Your id="+i+" will just set all anchor tags' IDs to +i+ because you are not escaping the plus sign and the variable i

You may try this, "a.a" should be "a.Chris" because Chris is the class name you have used not a andid should start with a non-numeric character.
for (var i = 0; i < neighbor.data[3].length; i++){
var a='<a class="Chris" name="a" id="id_'+i+'" href="Chris">Hi</a>';
$('#links').append(a);
}
$("#links").on("click", "a.Chris", function(event) { // You can use $(document).on(...) instead of $("#links").on(...)
event.preventDefault();
event.stopPropagation();
clickedID = parseInt($(this).attr("id").split('_')[1]);
alert(clickedID);
});
DEMO.

Related

jquery function not firing when I use datatable.fnAddData to append the HTML string

jquery function not firing when I use dataTable.fnAddData to append the HTML string.
So I have a function populateDataTable(), there are two columns I needed to render an icon instead of data from JSON.
Hence, I tried to like appending the HTML string including classes for the element in fnAddData(). But somehow it's not firing the click event on the icon.
function populateDataTable(data) {
$("#customerTable").DataTable().clear();
var length = Object.keys(data).length;
for(var i = 1; i < length+1; i++) {
var index = i - 1;
var name = data[index].name;
var queue = data[index].queue;
var expire = data[index].expire;
$('#customerTable').dataTable().fnAddData( [
i,
name,
queue,
'<td id="tb-manage-key" class="tb-manage-key"><div class="tb-btn manage-key-btn switch-view" data-hide="manageCustomers" data-title="#Resources.ManageKeys" data-target="manageKeys"><span></span></div></td>',
'<td class="tb-manage-subs"><div class="tb-btn manage-subs-btn switch-view" data-hide="manageCustomers" data-title="#Resources.ManageSubscriptions" data-target="manageSubscriptions"><span></span></div></td>',
expire,
name
]);
}}
$('.tb-btn.switch-view').on('click', function(e) {
e.preventDefault();
switchView(this);
console.log('Testing'); //not firing
});
Icon is showing, but not firing click event as it supposed to be. Attached below shows that we can see it appends the div as expected.
Solutions
Adding the click event within the populateDataTable() works.
$('#customerTable tbody').on('click', '.tb-btn.switch-view', function() {
switchView(this);
});
You can try a different syntax to listen to the click event...
$('td').on('click', '.tb-btn.switch-view', function(e) {
e.preventDefault();
switchView(this);
console.log('Testing'); //not firing
});

Apply A Function to All Links on Page

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)
}

Open page based on $(this) selector

I'm modifying a wordpress site and have a menu with four anchor tags (buttons) to the left of a slider. When a user selects a button, the slide associated with the button shows. Now, I'd like to open a page when the user clicks the button, instead of showing the slide. Here is the code so far:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$a = $(this);
$(this).showSlide();
if($a.id == $('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Here I'm testing to see if I can click on the anchor with the id '#slide-1285' and log it to the console. It always says 'not testing'. I'm going to set up conditions for all id's so a user is redirected to the correct page. Something like this:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$(this).showSlide();
if($a.id == $('#slide-1285')){
window.location.href = "http://webpage1";
}
elseif($a.id == $('#slide-1286')){
window.location.href = "http://webpage2";
}
elseif($a.id == $('#slide-1287')){
window.location.href = "http://webpage3";
}
else($a.id == $('#slide-1288')){
window.location.href = "http://webpage4";
}
});
Any ideas? Thanks in advance.
To get the id of the element that was clicked, you can do:
$(this).attr('id');
That will return a string. So you could do:
if($(this).attr('id') === 'slide-1285') { do something }
$('#slide-1285') would return a jquery element, but you want just the id. I think the code above is more what you are looking for.
You can add a new data attribute to each of your link and then get that value and redirect.
<a data-webpage="http://webpage1" href="whatever" id="slide-123"></a>
<a data-webpage="http://webpage2" href="whatever" id="slide-456"></a>
.....
and then
// this will bind all ids starting with slide-
$('[id^=slide-]').on('click', function(e){
// some code.
window.location.href = $(this).data('webpage');
}
1) you are comparing $a.id, that is string, to object $('#slide-1285');.
2) To simplify:
$(document).ready(function(){
$('.a').click(function(e){
e.preventDefault();
window.location = $(this).attr('href');
});
});
<a href='http://google.com' class='a'>Google!</a><br/>
<a href='http://stackoverflow.com' class='a'>SO!</a><br/>
jQuery objects have no id property. You need to do attr('id'), or just get the id property of the plain DOM object. Additionally, jQuery objects are never going to equal each other. Third, you want to check if the clicked element has a certain ID, which can be done using .is().
In sum, you could do one of these:
Comparing strings:
$('#slidernavigation > a').on('click', function(e){
if(this.id == '#slide-1285'){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Using .is():
$('#slidernavigation > a').on('click', function(e){
if($(this).is('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Or, just let the browser do its thing. Give your <a>s href attributes, and they'll function as links, even without JS.
instead of writing $.id
you should write
$a.attr('id')
and this should be checked like this :-
if( $a.attr('id') == slide-1285)
not the way you are doing :)
Try
var pages = [{"slide-1285" : "http://webpage1"}
, {"slide-1286" : "http://webpage2"}
, {"slide-1287" : "http://webpage3"}
, {"slide-1288" : "http://webpage4"}
];
$('#slidernavigation > a').on('click', function(e) {
e.preventDefault();
var nav = e.target.id;
$.grep(pages, function(page) {
if (nav in page) {
window.location.href = page[nav];
}
})
});
jsfiddle http://jsfiddle.net/guest271314/2nf97dfr/
<div id="a">
dhjdfd
</div>
$('#a').on('click',function(e){
var clickedElement= e.srcElement;
if($(clickedElement).attr("id") == "abc"){
//do something
}
});
just use e.srcElement to get the element reference and then get its id.. and btw u can use switch case rather than multiple if else statements ..
working fiddle link

By JQuery, how to specify on function as onClick handler for many radio buttons?

I have a function called handleOnClickRadio(i, j); and lots of radio buttons named as id="something-radio[i][j]". All these radio buttons are in a table called "bigtable".
How could I attach the function handleOnClickRadio() to all these radio buttons? And call it correct with handleOnClickRadio(i,j).
Thanks.
I would not attach the click handler to the buttons at all. You say you have lots of them. Attaching the same event handler to each of them is a waste of memory and could even be a performance problem.
Use event delegation instead:
$('#tableID').delegate('input[type=radio]', 'click', function() {
// code here
});
Then you could extract the i and j via regular expression (you could also consider to change the pattern so that you can use something simpler like split()):
var exp = new RegExp("\\[(.+?)\\]\\[(.+?)\\]", 'g');
var match = exp.exec(this.id);
var i = match[1];
var j = match[2];
You could put this together like so:
$('#tableID').delegate('input[type=radio]', 'click', function() {
var match = this.id.match(/\[(.+?)\]\[(.+?)\]/)
var i = match[1]; // use parseInt(match[1]) if you need an integer
var j = match[2];
handleOnClickRadio(i,j);
});
edit: Made code a bit simpler.
If i and j correspond to column and row indicies, see #Caspar Kleijne's answer for an alternative way to retrieve them.
For accessibility, you should consider binding the handler to the change event. Then changes via the keyboard will be recognized too.
wire up the event like this
$("#bigtable input[type='radio']").bind("click", OnClickRadio);
and use the handler like
var OnClickRadio = function () {
var col = $(this).parent("td").index();
var row = $(this).parent("td").parent("tr").index();
handleOnClickRadio(col, row)
});
You can attach an onClick method to a collection of radio buttons within a table with a simple bit of jQuery. When you say 'table called "bigtable"', I'm assuming that you mean that it has id="bigtable" in the following code.
$(document).ready(function() {
$("#bigtable input:radio").click(function() {
// Your on click code here
});
});
However, I would usually give each of the radio buttons a specific class using class="magicRadioButton" and then your jQuery code becomes a little clearer and doesn't rely on all of those radio buttons being within a table;
$(document).ready(function() {
$(".magicRadioButton").click(function() {
// Your on click code here
});
});
Now, if you need to then plug this information into your current handleOnClickRadio method, you can do so with the following.
$(document).ready(function() {
$("#bigtable input:radio").click(function() {
var button_id = $(this).attr("id");
var re = new RegExp("\\[(.*?)\\]\\[(.*)\\]");
var matches = re.exec(button_id);
var i = matches[1];
var j = matches[2];
handleOnClickRadio(i,j);
});
});
Give them class names in conjunction with $(this) in your click trigger
I suggest using delegate if you have lot of radios: that way, only one Event listener will be attached
see http://api.jquery.com/delegate/
$("#globalContainer").delegate("input", "click", function(){
//Perform a string test / regex to test if the id matches something-radio[i][j]
//With a regex with capturing groups you can retrieve [i] and [j] values at the same time
if ( test($(this).attr("id")) ) {
}
});
Ideally, you'd have a onclick assigned to the big table rather than each and every radio button. Events in JavaScript bubble up so the table (which is the eventual parent of all these radio buttons) will receiving the event.
So in jQuery you would have code like this
$('#bigtable').click(handleOnClickRadio);
The signature of your handleOnClickRadio function would be
function handleOnClickRadio(evt) {
var radio = evt.target;
var id = $(radio).attr('id');
}
evt.target will identify the actual radio button that was clicked/checked and you can access other attributes of the radio as well. such as
$(radio).attr('id)
Will give you the id of the radio button.
<input type="radio" class="many-radio-buttons" ....
jQuery:
$('.many-radio-buttons').click(function() {
//your_code;
});

jQuery ~ Adjusting href before following it

I have a link with a series of checkboxes, due to the legacy code, when the user clicks on a checkbox the value of it is appended as a comma deliminated list to the href.
The trouble is that now that I'm updating the code, I'm finding that the href is being followed quicker than the href is being adjusted, thus the list is being excluded.
I have tried using preventDefault() which is great, but I have no idea how to continue the default action after changing the href to include the selected values.
I should also mention that it is not viable to change it to a regular form, as there is an additional option set in a lightbox after submission. (Don't ask me why, it's lunacy in my book)
So far I've got to
$(function(){
$('#cnt-area form table tbody').dragCheck();
// I just split up the .each and .click to see if it mattered, which it doesnt
$('.multi_assign_link').each(function(){
$(this).click(function(e){
e.preventDefault();
var href = $(this).attr('href');
$('#cnt-area form input:checkbox').each(function(){
if($(this).attr('checked')){
if(href.search(','+$(this).val()) == -1){
href += ','+$(this).val();
}
}else{
var s = ','+$(this).val();
s.toString();
href = href.replace(s, '');
}
});
$(this).attr('href',href);
// Continue to follow the link
// Faking a user click here with $(this).click(); obviously throws a loop!
});
});
});
Just set the location to the adjusted href value and return false from the handler to avoid taking the original link.
$(function(){
$('#cnt-area form table tbody').dragCheck();
// I just split up the .each and .click to see if it mattered, which it doesnt
$('.multi_assign_link').each(function(){
$(this).click(function(e){
var href = $(this).attr('href');
$('#cnt-area form input:checkbox').each(function(){
if($(this).attr('checked')){
if(href.search(','+$(this).val()) == -1){
href += ','+$(this).val();
}
}else{
var s = ','+$(this).val();
s.toString();
href = href.replace(s, '');
}
});
location.href = href;
return false;
});
});
});

Categories

Resources