I have unordered list of links and i am trying to get the clicked link text.
So when i click on some link i would like to display in paragraph or textbox at the bottom of my list text that is cliked.
So if I have something like this:
item1
item2
item3
If i click on item2 i would like to get it like: "You just clicked:item2 "
And i manage that with this:
jQuery(function () {
$('a').click(function () {
alert('Text is: ' + $(this).text());
});
});
But that is displaying an alert message. then i do this:
jQuery(function () {
$('a').click(function () {
var name = $(this).text();
$("p#selector").text(name);
$("input#textbox").val(name);
});
});
And it works it send text value of a link to paragraph but it disappear really fast, it show it about second and it's gone, is there any way to prevent this? To stop it from disappearing?
Try this:
jQuery(function () {
$('a').click(function (e) {
e.preventDefault();
var name = $(this).text();
$("#selector").text(name);
$("#textbox").val(name);
});
});
e.preventDefault() will prevent the link from doing whatever it is doing by default (which sounds like it could be refreshing the page...).
Here's a demo.
I've also amended your selectors - p#selector is inefficient, you should simply use #selector when selecting by ID, as documented in the jQuery API.
For id selectors, jQuery uses the
JavaScript function
document.getElementById(), which is
extremely efficient. When another
selector is attached to the id
selector, such as h2#pageTitle, jQuery
performs an additional check before
identifying the element as a match.
EDIT: As it's become apparent that the click handler isn't what you need here, try this solution:
Parse the URL to get the current page using a jQuery URL Parser, and then find the link that corresponds to the URL and get the text:
var url = "one.htm";
var linktext = $("a[href='" + url + "']").text();
$('#output').text(linktext);
Working demo of that bit (just do the URL parsing instead of setting the URL manually).
Try preventing the click event from propagating after you handle it by returning false from the function.
jQuery(function() {
$('a').click(function () {
var name = $(this).text();
$("p#selector").text(name);
$("input#textbox").val(name);
return false;
});
});
EDIT 1: Which is functionally identical to the answer provided by #Town, who beat me to it
EDIT 2: return false is not quite identical to .preventDefault() (which prevents the default event from occurring, but does not prevent other registered handlers from firing) or indeed .stopPropagation() (which stops event 'bubbling' and prevents handlers further up the DOM from firing). Returning false causes both but as #Town says, if the handler errors before returning, the default event will occur.
Basically... do what he said.
Related
I have a tag with href="tel:XXXXXXXXX", and I need catch the click event.
I have tested the following code on chrome: $(document).on('click',console.log). If i click on this tag browser it calls the application, but does not trigger a click event.
$("a[href^='tel']").on('click', console.log);
This is working, but I my have a problem with content load by ajax. My code has loaded a page and after some time application added content by ajax. When i use $(document).on('click', ("a[href^='tel']", console.log), there is a problem.
$("a[href^='tel']").on("click", function(e){
e.preventDefault(); e.stopPropagation();
console.log(this);
alert(this.getAttribute("href"));
})
//or if you want to delegate your function
$(document).on('click', "a[href^='tel']", function(e){
e.preventDefault(); e.stopPropagation();
console.log(this);
alert(this.getAttribute("href"));
});
This will bind an event listener to all click on a tags with a href attribute and prevent the click itself. After click, you'll be able to use your console to see which element was click and what href was used.
Ok, i found resolve.
I use earlier event "mousedown" and change attr "href" to "only number" for disable action click.
Code:
const click2dial_Event = function(e) {
e.preventDefault();
let a = $(this), number;
if (a.attr('href') !== '#') {
number = a.attr('href');
number = number.substr(4);
a.attr('href', '#');
a.attr('data-dial', number)
a.addClass('click-to-dial');
} else {
number = a.attr('data-dial');
}
//...
};
$(document).on('mousedown', "a[href^='tel']", click2dial_Event);
$(document).on('mousedown', '.click-to-dial', click2dial_Event);
This would get the phone number from the a tag starting with a value of tel upon clicking it.
$("a[href^='tel']").on("click", function(e) {
var hrefText = this.getAttribute("href");
var str = hrefText;
var res = str.split(":");
alert(res[1]);
});
On Initial Load
I would first recommend that you wait for the initial DOM to be ready before binding any events to elements.
// DOM ready shorthand
$(function() {
$("a[href^='tel']").on('click', function(e) {
// Do work here
});
});
AJAX Content
If you are adding additional elements after the initial load you will have to bind events to those new elements as well.
You could also do something like adding a data attribute to the elements that you've bound click events to and only add to ones that don't yet have that data attribute - but that's additional unnecessary work.
Full Example Code
// DOM Ready Shorthand
$(function() {
// Click Handler
function clickEvent(e) {
// Do work here
}
// Bind click event to initial tels
$("a[href^='tel']").on('click', clickEvent);
// Arbitrary AJAX request for demonstration (wherever yours may be)
$.ajax('/newContent')
.done(function(html) {
// Adding our response HTML to the page within #someElement
$('#someElement').append(html);
// Bind click event to the new tel elements scoped to the returned html
$("a[href^='tel']", html).on('click', clickEvent);
});
});
Content script:
var $ = window.$.noConflict(true); // Required for IE
function startFunc() {
$('a').mouseover(function(e){
var anchor=this;
var href=$(anchor).attr('href');
if(href!='#'){
$('.klik-me').remove();
const xPos=e.pageX-20;
const yPos=e.pageY-20;
let $klikMe=$('<span class="klik-me">Click Me!!</span>').css({
'padding':'5px',
'background':'#000',
'color':'#FFF',
'font-size':'12px',
'position':'static',
'top':yPos,
'left':xPos,
'text-align':'center',
'z-index':999999
});
$(anchor).append($klikMe);
}
});
}
$('body').on('click','.klik-me',function(){
const href_in=$(this).parent().attr('href');
kango.console.log(href_in);
kango.dispatchMessage('storeHref', {href:href_in});
});
kango.addMessageListener('hrefSuccess', function(event) {
kango.console.log(event.data.link);
});
Background Script:
kango.addMessageListener('storeHref', function(event) {
event.target.dispatchMessage('hrefSuccess', {link:event.data.href});
});
I am adding a pop up for all anchor tags on the page (this is working fine),i added a click event in Jquery(I love this) and using kango.dispatchMessage for sending message to background script. Nothing seems to be working.
Any help would be appreciated.
PS: i use to work with crossrider(Awesome) framework previously.
What I think is happening is the click event is bubbling up to your <a> element and triggering the default navigation action.
Stopping bubbling / default behaviour in delegated event handling is difficult. What I would do instead, is remove the <span> as a child of the <a>. For example
let $klikMe = $('<span class="klik-me">Click Me!!</span>')
.css({ ... })
.data('href', href) // set the href data into the <span>
$(document.body).append($klikMe) // append to body, not anchor
and in your click handler
$(document).on('click', '.klick-me', function() {
const href_in = $(this).data('href')
// then continue as in your original code
return false // the click should have no default action
})
Use the snippet below is what I'm reading everywhere, I can't get it working however.
Currently trying to do somewhat the same: jQuery click event after new page loads
Maybe it can be of some use.
Cheers.
$(parent).on('click', child , callback);
I currently have the following in a document.ready block:
$("[id^=summaryDetailLink_]").each(function(index) {
var splitID = this.id.split("_");
this.click(alert('clicked: '+splitID[1])); //toggleDetail(splitID[1])
});
Ultimately I want to detect when a TD with an ID of "summaryDetail_" is clicked on and fire the toggleDetail function with the ID taken from the TD.ID attribute.
The above seems to generate the correct ID (the alert popsup) but is firing when the page loads rather than when I click on the element.
So problem number 1 - why is it firing on page load rather than creating a handler for click on each element and waiting for that click?
Problem number 2, in reading around this issue it seems it would be more sensible to create a single event handler on the table rather the TD then determine which TD element was clicked. How would I convert the code to do that?
Answer to first question:
$(function() {
$("[id^=summaryDetailLink_]").click(function() {
var splitID = $(this).id.split("_");
alert('clicked: '+splitID[1])
});
}
Answer to second question, you can do this:
$('table#yourtable').on('click', '[id^=summaryDetailLink_]', function(e) {
var splitID = $(this).id.split("_");
alert('clicked: '+splitID[1])
});
I think you're misunderstanding how the click handler works:
$(function() {
$("[id^=summaryDetailLink_]").click(function() {
var splitID = $(this).id.split("_");
alert('clicked: '+splitID[1])
});
}
I am trying to add an onClick event to an anchor tag ...
Previously i had ...
<a href="somlink.html" onClick="pageTracker._link(this.href); return false;">
But i am trying to avoid the inline onClick event because it interferes with another script..
So using jQuery i am trying the following code ...
<script>
$(document).ready(function() {
$('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null;
pageTracker._link(this.href);
return false;
});
});
</script>
with the html like so <a id="tracked" href="something.html">
So my question is should this be working, and if not what would be the best solution?
The correct way would be (as for jQuery)
$('#tracked').click(function() {
pageTracker._link($(this).attr('href'));
return false;
});
This will add an "onclick" event on any element with tracked id. There you can do anything you want. After the click event happens, the first line will pass href attribute of the clicked element to pageTracker.
As for your original question, it wouldnt work, it will raise undefined error. The attr works a bit different. See documentation . The way you used it, would return the value of the attribute and I think that in that case its not chainable. If you would like to keep it the way you had it, it should look like this:
$('#tracked').click(function() {
$(this).attr('onclick', 'pageTracker._link(this.href); return false;');
return false;
});
You can also try
var element1= document.getElementById("elementId");
and then
element1.setAttribute("onchange","functionNameAlreadyDefinedInYourScript()");
// here i am trying to set the onchange event of element1(a dropdown) to redirect to a function()
I spent some time on this yesterday. It turned out that I needed to include the jQuery on $(window).ready not $(document).ready.
$( window ).ready(function() {
$('#containerDiv a').click(function() {
dataLayer.push({
'event': 'trackEvent',
'gtmCategory': 'importantLinkSimilarProperties',
'gtmAction': 'Click',
'gtmLabel': $(this).attr('href')
});
});
});
I think I've been too much time looking at this function and just got stuck trying to figure out the nice clean way to do it.
It's a jQuery function that adds a click event to any div that has a click CSS class. When that div.click is clicked it redirects the user to the first link found in it.
function clickabledivs() {
$('.click').each(
function (intIndex) {
$(this).bind("click", function(){
window.location = $( "#"+$(this).attr('id')+" a:first-child" ).attr('href');
});
}
);
}
The code simply works although I'm pretty sure there is a fairly better way to accomplish it, specially the selector I am using: $( "#"+$(this).attr('id')+" a:first-child" ). Everything looks long and slow. Any ideas?
Please let me know if you need more details.
PS: I've found some really nice jQuery benchmarking reference from Project2k.de here:
http://blog.projekt2k.de/2010/01/benchmarking-jquery-1-4/
Depending on how many of these div.click elements you have, you may want to use event delegation to handle these clicks. This means using a single event handler for all divs that have the click class. Then, inside that event handler, your callback acts based on which div.click the event originated from. Like this:
$('#div-click-parent').click(function (event)
{
var $target = $(event.target); // the element that fired the original click event
if ($target.is('div.click'))
{
window.location.href = $target.find('a').attr('href');
}
});
Fewer event handlers means better scaling - more div.click elements won't slow down your event handling.
optimized delegation with jQuery 1.7+
$('#div-click-parent').on('click', 'div.click', function () {
window.location.href = $(this).find('a').attr('href');
});
Instead of binding all the clicks on load, why not bind them on click? Should be much more optimal.
$(document).ready(function() {
$('.click').click(function() {
window.location = $(this).children('a:first').attr('href');
return false;
});
});
I would probably do something like;
$('.click').click(function(e){
window.location.href = $(this).find('a').attr('href');
});