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);
Related
I need to add/remove a class upon button click. For some reason, classList.toggle will not work but classList.add works fine.
document.querySelectorAll('.view-now').forEach( function (){
this.addEventListener('click', function(e) {
const property = e.target.closest('.property');
property.classList.toggle('expand');
});
});
Could you please change the this in the forEach since its referring to the document context instead of the specific a tag. In the original code, the page was listening for a click on the entire page, which was causing the issue you were facing.
/**** Your JS Here ****/
//define DOM element
//this makes whatver you click dissappear both boxes
document.querySelectorAll(".view-now").forEach(function(item) {
item.addEventListener("click", function(e) {
const property = e.target.closest(".property");
property.classList.toggle("expand");
});
});
Codepen
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);
});
});
I have a button and when it is clicked it should add a class to the HTML element, but then when the .class is clicked, it isn't detected.
This is the use case:
Click button - "testerclass" will be added to HTML element
Click "testerclass" - removes that class from that element
The detection for when "testerclass" is clicked only seems to work when the class exists before the page load, not when I add the class manually after load. Is this something to do with the problem?
I have tried to recreate the problem on jsfiddle, but I can't recreate the use case where the class is already added to the HTML element, as I can't edit that on jsfiddle.
But here is jsfiddle one, In this one you can see that the buttonone adds a class to HTML, but the detection for clicks on .testerclass never come through.
And here is jsfiddle two. In this one, I have changed the .testerclass selector to html, and this shows that HTML clicks are bubbling through (which I was unsure of when I first hit this problem).
And offline I created a third testcase where the HTML element already had the testerclass, and it detected the clicks sent through to it.
$(document).ready(function() {
$('button.1').click(function() {
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$('.testerclass').click(function() {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
});
Edit: I also tried doing this with a slightly different method of:
$('html').click(function() {
if(this).hasClass('testerclass') {
//do stuff
}
});
but that didn’t work either.
Since the testerclass is dynamic, you need to use event delegation to handle events based on that. Which will require us to register the event handler to the document object that causes another problem because the click event from the button will get propagated to the document object which will trigger the testerclass click handler as well. To prevent this from happening you can stop the event propagation from the button.
$(document).ready(function () {
$('button.1').click(function (e) {
e.stopPropagation();
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$(document).on('click', '.testerclass', function () {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
});
Demo: Fiddle
You need to stop the propagation to the html so the other click handler does not pick it up.
$('button.1').on("click", function(evt) {
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
evt.stopPropagation();
});
$(document).on("click", function() {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
Other option would be to add one event handler and use the event target to see if it is the button or not and change the content that way.
$(document).on("click", function (evt) {
var isButton = $(evt.target).is(".btn");
var message = isButton ? '<p>"testerclass" added to html</p>' : '<p>"testerclass" clicked and removed</p>'
$('html').toggleClass('testerclass', isButton);
$(".test").append(message);
});
JSFiddle: http://jsfiddle.net/69scv/
here's a neat way to do it
$('html').on('click', function(e) {
var state = !!$(e.target).closest('button.1').length;
var msg = state ? 'class added' : 'class removed';
$(this).toggleClass('testerclass', state);
$('.test').append(msg + '<br>');
});
FIDDLE
You add a class to html element, so when this class is clicked, it means the html element is click. Now the problem is when you click any where in page, it will remove this class away from html! Let try add this class to body element instead.
$(document).ready(function() {
$('button.1').click(function() {
$('body').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$('.testerclass').click(function() {
$('.test').append('testerclass clicked and removed<br />');
$('body').removeClass('testerclass');
});
});
And now you can check it:
$('html').click(function() {
if(this).hasClass('testerclass') {
//do stuff
}
});
I am using a drop down widget called Chosen which has an anchor with a href javascript:void(0). When I click on the drop down it works but on IE it fires a new onbeforeunload event which is frustrating because the application confirms if you want to leave. And obviously you don't want to have those questions when you are inputting form data.
Is there a way to get rid of this problem without altering Chosen library?
Unfortunately this:
window.onbeforeunload = function (e) {
console.log(window.location);
};
Does not log javascript:void(0) either, so, I can't use it to check the target URL.
This behavior occurs in IE9 at least, and that's what I'm concerned (not the older IEs).
The only solution I can see is to add returning of false to the onclick event handler of the links. It will tell IE that you're not planning to change the page by clicking on the link.
Link
The same can be written this way:
<script>
function doSomething() {
// do Something
return false;
}
</script>
Link
I ended up listening to click events against the anchor and cancel the event to prevent onBeforeUnload from firing:
$chosen.find('.chzn-single').click(function() {
return false;
});
I know that this is pretty old...But I have come across this recently for my work. We are unfortunately still forced to support IE9. We are using Angular.js on this project that will dynamically load new content onto a page when the user clicks on an anchor tag with a data-ng-click.
In your example all you would have to do is pass the event and within the function prevent the default action and stop it from bubbling up. To do this all you would have to do is this:
// Inside the HTML
{...}
Link
{...}
<script>
function doSomething(evt) {
evt.preventDefault();
evt.stopPropagation();
// Do Something
};
</script>
{...}
In Angular all I did was the following:
// Inside the View
Add Stuff
// Inside the controller
function addStuff($event) {
$event.preventDefault();
$event.stopPropagation();
// Do Something
};
I hope that this isn't too late and I hope that it helps others.
Had the same problem. Just found your question. My solution is, you need to add onclick attribute to every chosen dropdown list anchor tag and call window.onbeforeunload = null
In my case, I've put
$(".chzn-single").attr("onclick", "window.onbeforeunload = null;");
After setting up chosen library and it works fine
don't use href's for this. A simple solution with minimal extra work:
i prefer to use a CSS class that simulates an href, obviously you will change the color and styling of this class to fit your website, but for this purposes, it's the standard blue underlined link
<style>
.linkSimulate
{
cursor: pointer;
COLOR: blue;
text-decoration: underline;
}
</style>
then use a simple anchor
<a onclick = "do_save();" class ="linkSimulate">Link</a>
Even if this question is old, i've anhanced the answer of #Bartosz, fixing the issue in the comment of #Oiva Eskola:
Wouldn't this prevent the window.onbeforeunload from working after clicking a chosen link element? – var thisOnClick;
Below is my solution to properly create the HTML onclick property, to not override or cancel the event:
var thisOnClick;
$.each( $(' .container a '), function(){
thisOnClick = $(this).attr('onclick');
if ( typeof thisOnClick == 'undefined' ) {
$(this).attr('onclick', 'window.onbeforeunload = null;');
} else if ( typeof thisOnClick == 'string' && thisOnClick.indexOf('window.onbeforeunload') == -1 ) {
$(this).attr('onclick', thisOnClick + 'window.onbeforeunload = null;');
}
});
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');
});