Stoping a link from executing it's href path - javascript

Hi I am trying to stop a link from executing it's default action , but I seem to have no luck.Here is my code:
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
});
var lightbox = {
init : function(actionString){
$("<div id='lightbox-background'></div>").appendTo("body");
$("<div id='lightbox'></div>").appendTo("body");
$("<p></p>").appendTo("#lightbox");
$("<a href='#' id='ok'>OK</a>").appendTo("#lightbox");
$("<a href='#' id='cancel'>Cancel</a>").appendTo("#lightbox");
}
}
I hoped that if I used e.preventDefault it would stop the link from from going to it's href path but it did not work.Am I doing something wrong?
EDIT: I just noticed that if I remove the call for the lightbox object from the click event handler the e.preventDefault() works.

Your problem is in this line:
var lightbox = $("#lightbox");
in onclick callback function hide
variable name is the same as name of global lightbox object defined outside click callback. Local variable mentioned above simply override global variable inside that function scope. Basically, you are calling init of $("#lightbox"):
$("#lightbox").init("....")
Not sure what are you doing, but try to update your code like this:
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightboxElement = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
});
Besides, calling
var container = $("#lightbox-background");
var lightboxElement = $("#lightbox");
at the first time, you will get an empty set of elements as init method is not executed at that moment and elements you are looking for are not created yet.

Try if it works
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
return false;
});

Have you tried it above the vars declared:
$("a.delete").on("click", function (e) {
e.preventDefault();
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
});
Just noticed that you have missed a ';' at closing here:
var lightbox = {
init : function(actionString){
$("<div id='lightbox-background'></div>").appendTo("body");
$("<div id='lightbox'></div>").appendTo("body");
$("<p></p>").appendTo("#lightbox");
$("<a href='#' id='ok'>OK</a>").appendTo("#lightbox");
$("<a href='#' id='cancel'>Cancel</a>").appendTo("#lightbox");
}
}; //<----this one

Example for a link like:
google
use javascript with jQuery
$("a").click(function(e){e.preventDefault(); return false;});
this will not redirect any link on the page :)
or in given case it will be like
$("a.delete").click(function(e){e.preventDefault(); return false;});
Note: Added e.preventDefault(); to prevent the event from triggering.

Related

EventListener's e.preventDefault(); not working for inner-page href="#hash" links

I am currently building a WordPress site and trying to prevent inner page links for firing. The part of code I use is:
var numberLinks = Array.from( document.querySelectorAll('.benefits-links .inner-nav-link > .number-link '));
numberLinks.forEach( function (link) {
link.addEventListener('click' , numberClick)
})
function numberClick(e) {
e.preventDefault();
console.log(e);
}
When a <a></a> tag is clicked the event is logged but the window still jumps to the href anchor.
Am I missing something? How to stop the execution of the link and add my own functions?
Page of reference is https://dev.cognitivplus.com/grey-box/
Thank you
Just to make a contribution, what made the trick was to add:
e.preventDefault();
e.stopPropagation();
apparently, some relative element was triggering the link
Try bellow codes, it will work :
numberLinks.forEach( function (link) {
link.addEventListener('mouseenter',function(e){
var myLink = e.currentTarget;
myLink.khref = myLink.href;
myLink.href = "#";
});
link.addEventListener('mouseout',function(e){
var myLink = e.currentTarget;
myLink.href = myLink.khref
});
});
Hi I do it this way,
I use a specific class for all the elements i dont want to trigger.
var numberLinks = document.querySelectorAll('.benefits-links');
console.log(numberLinks);
numberLinks.forEach( function (link) {
link.addEventListener('click' , (e)=>{
e.preventDefault();
console.log("anything will trigger except pokemon");
return false
})
})
.benefits-links{
color:red;
}
Google
<br>
Pokemon
<br>
Stack Overflow
Hope it helps

Run function on active anchor

I'm new to jQuery and want to highlight div's if the div's anchor id is set.
I currently have this construct which only works on page load with an valid anchor attached.
$(document).ready(function(){
var divpost = window.location.hash.substr(1);
if($.isNumeric(divpost)){
$('#reply_' + divpost).css('background-color', '#EDA2FF');
}
});
This works only on page load with a set anchor. How can I make this more dynamic so the script executes whenever the anchor changes?
jQuery can hook into the hashchange event so you can do this:
$(window).on('hashchange', function(e){
var divpost = window.location.hash.substr(1);
if($.isNumeric(divpost)){
$('#reply_' + divpost).css('background-color', '#EDA2FF');
}
});
You can make it a function and call it with every update.
function updateAnchors() {
var divpost = window.location.hash.substr(1);
if($.isNumeric(divpost)){
$('#reply_' + divpost).css('background-color', '#EDA2FF');
}
}
Then call updateAnchors() when more anchors are loaded.

.click() jQuery function works for one ID but not variable

I have this code in my js file and basically what I want to test out is, if the user clicks on a certain button (which has ID of admin).
I want it to bring up a closeButton which is png image and then when the user clicks this again it should disappear. To test of the button functions are responsive I have put alerts in the functions.
Clicking on the initial button works, the function finds the corresponding ID, makes the alert("jQuery Worked") line and brings up the closeButton image.
However when I click on the close button nothing happens (we expect here that the alert("hiii") would work but it doesn't. I have looked online and found that my code needed to be in a $(document).ready(function() {} function which it is but it isn't working. I also tried to use the ID of the image to make the closeButton image disappear but that didn't work either. So I have tried just using the $closeButton variable which I thought for usre should work but doesn't. Why?
.js file
var $closeButton = $("<img>");
$(document).ready(function() {
$("#admin").click(function (event) {
var $overlay = $("<div id='overlay'> </div>");
var $closeButton = $("<img class='classMe' id='closeButtonID' src='https://s23.postimg.org/ouup1ib6z/close_button.png'></img>");
$("body").append($overlay);
$overlay.append($closeButton);
alert("jQuery worked");
});
$closeButton.click(function() {
alert("hiiii");
});
});
you looking for Event delegation.
Event delegation refers to the process of using event propagation
(bubbling) to handle events at a higher level in the DOM than the
element on which the event originated. It allows us to attach a single
event listener for elements that exist now or in the future. Inside
the Event Handling Function.
$(document).on('click', '#closeButtonID', function() {
alert('hiii');
});
Do this:
$(document).ready(function() {
$("#admin").click(function (event) {
var $overlay = $("<div id='overlay'></div>");
var $closeButton = $("<img id='closeButtonID' src='https://s23.postimg.org/ouup1ib6z/close_button.png'></img>");
$("body").append($overlay);
$overlay.append($closeButton);
alert("jQuery worked");
});
$(document).on('click', '#closeButtonID', function() {
alert('hi');
});
});
Not a good way to do this but it's a different way to solve the problem , Hope it will help you :
var $closeButton = $("<img>");
$(document).ready(function() {
$("#admin").click(function (event) {
var $overlay = $("<div id='overlay'> </div>");
var $closeButton = $("<img class='classMe' id='closeButtonID' src='https://s23.postimg.org/ouup1ib6z/close_button.png'></img>");
$("body").append($overlay);
$overlay.append($closeButton);
alert("jQuery worked");
close();
});
function close(){
$('#closeButtonID').click(function() {
alert("hiiii");
});
}
});
JSFIDDLE

Modify target url in onclick handler

Is it possible to modify the target URL in the onclick handler? How?
I don't want to use things like window.location = ... because it changes the browsers' behaviour (click vs ctrl-click, opening in new tab, opening in particular window/frame etc...). I want a clean solution - just change the url and the rest should be done itself as it would normally be.
$(...).click(function () {
if (check_some_condition)
// modify target url here...
// do not want to do window.location= - this is not clean
// as it changes the browsers' behaviour (ctrl-click, opening in particular window/frame etc.)
return true;
});
Try
​$(function(){
$("#theLink").click(function(){
$(this).attr("href","http://tnbelt.com");
});
});​​​​
Edit: Updated code because the event handler script is executed first and then the default action takes place.
Added below version to show you that you can use .click as you didn't notice the quirks mode link I shared with you. DEMO
$(document).ready (function () {
$('#changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
Commented e.preventDefault(); & $(this).click() as it is not required..
DEMO
$(document).ready (function () {
$('#changeMe').one ('click', function (e) {
//e.preventDefault();
this.href = "http://www.google.com";
//$(this).click();
});
});
Let us consider a hidden anchor tag
<a id="linkId" href="myPageToGo.html" class="thickbox" title="" style="visibility:hidden;">Link</a>
Then you can simulate the anchor click in your code...
$(...).click(function () {
if (check_some_condition)
$('#linkId').click();
return true;
});
EDIT - Alternative way
Wrap the element clicked inside a anchor tag...
$(...).click(function () {
if (check_some_condition)
$(this).wrap('<a id="new1" />');
$('#new1').click();
return true;
});
Yup.
$(this).attr('href', 'http://example.com/');
A lot of the answers including the top comment have missed out on an important point. If a user simply right clicks the URL to perhaps open in a new tab/window, this method won't work because you're directly requesting at the location specified by the 'href' URL instead of going through the onclick event.
You could try the same at this demo fiddle mentioned on Gourneau's post.
http://jsfiddle.net/skram/PtNfD/7/
$(document).ready (function () {
$('#changeMe').one ('click', function (e) {
this.href = "http://www.google.com";
});
});

Hack: Disable click click with jQuery

I'm hacking a gallery plugin where I want to disable the click event for the thumbnail and replace it with a hover event.
This is what I did: http://jsbin.com/enezol/3
$(function() {
var galleries = $('.ad-gallery').adGallery();
$('.ad-thumb-list a').hover(function() {
$(this).click();
});
$('.ad-thumb-list a').click(function() {
return false;
});
});
The plugin doesn't allow me to set event to use. So Instead of changing it from their code, I'll just add a little tweak on top of it.
So I want to disable the click event for the 'thumbnail' and just use 'hover' event instead.
Any got and ideas? I'm also open to other approach as long as it meets my requirement.
Thank You!
Trying to implement Steph Skardal and Nicosunshine suggestion:
var thumbs = $('.ad-thumb-list a'),
oldfunction = thumbs.data("events").click["function () { context.showImage(i); context.slideshow.stop(); return false; }"];
thumbs.unbind("click").hover(oldFunction);
edit: My Solution:
I use return false to restrict it from going to the url but it does not restrict in calling the function. Any alternative ideas?
var galleries = $('.ad-gallery').adGallery();
var thumbs = $('.ad-thumb-list a');
thumbs .hover(
function () {
$(this).click();
},
function () {
}
);
thumbs.click( function () { return false; });
You want to use jQuery's unbind method, to unbind the click event. It will have to be called after the plugin is called. E.g.:
$('.ad-thumb-list a').unbind('click');
You could try to unbind the click method and then bind the original function to the hover.
If you can't get the original function you can get it by seeing what the console returns if you throw:
$('.ad-thumb-list a').data("events").click; //name of the property that has the function
then you grab that function and do:
var thumbs = $('.ad-thumb-list a'),
oldfunction = thumbs.data("events").click["theValueYouGotInTheConsole"];
thumbs.unbind("click")
.hover(oldFunction);
Edit:
Here is an example of what I ment with "theValueYouGotInTheConsole", in the image I'm accessing the click property, and then the "4" is where the function is stored.
If you don't want to hardcode the value you can do:
var dataEvents = thumbs.data("events").click,
oldFunction;
for(var functionEvent in dataEvents) {
oldFunction = dataEvents[functionEvent];
break; //I'm assuming there's only one event
}

Categories

Resources