How to assign default action to right click? - javascript

Don't know how to make it work, but I guess it's part of the learning process... Bellow is the code with two links, on that needs to be redirected, second one, regular... I want to make it that mouse actions on both links are identical (open on left click, open in new tab with middle click, properties on right click). Thank you all for your input.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a id="googlelink" href="https://www.google.com">Google</a>
<hr>
Google
<hr>
<script>
document.getElementById("googlelink").addEventListener("click", redirectToYahoo);
document.getElementById("googlelink").addEventListener("auxclick", redirectToYahooNewTab);
document.getElementById("googlelink").addEventListener("contextmenu", rightClick);
function redirectToYahoo() { // LEFT MOUSE CLICK
window.location.href = "https://www.yahoo.com";
}
function redirectToYahooNewTab() { // MIDDLE MOUSE CLICK
window.open('https://www.yahoo.com', '_blank');
}
function rightClick() { // RIGHT MOUSE CLICK
event.preventDefault();
};
</script>
</body>
Here is the snippet from #charlietfl that did the job.
var link = document.getElementById('googlelink');
link.addEventListener("auxclick",function(e){
if(e.button !==2){
window.open('https://www.yahoo.com', '_blank');
}else{
e.preventDefault()
}
});
link.addEventListener('click', function(e){
window.location.href = "https://www.yahoo.com";
});
link.addEventListener('contextmenu', function(e){
});

The problem is in your auxclick. Need to check which mouse button was used.
Not sure why you are using auxclick ... it has limited browser support.
A normal click listener won't trigger for right click. Also event name is contextmenu not oncontextmenu
var link = document.getElementById('test');
link.addEventListener("auxclick",function(e){
if(e.button !==2){
console.log('Aux normal');
e.preventDefault();
}else{
console.log('Aux right click')
}
});
link.addEventListener('click', function(e){
console.log('Normal click')// no log when right click
e.preventDefault() // just for demo
})
link.addEventListener('contextmenu', function(e){
console.log('Context menu')
e.preventDefault()
})
<a id="test" href="/questions">Stackoverflow Questions</a>

Not sure if this solves your auxclick issue, but it answers how to do the rightclick as per the title:
Change oncontextmenu to contextmenu. Then prevent the default event:
document.getElementById("googlelink").addEventListener("contextmenu", rightClick);
function rightClick() {
event.preventDefault();
alert("Right click disabled");
// do your stuff here
};
<button id="googlelink">googlelink</button>

I hope this can be helpful:
var link = document.getElementById("googlelink");
document.addEventListener('DOMContentLoaded', e => {
replace();
});
function replace() {
link.href = "https://www.yahoo.com";
}
<a id="googlelink" href="www.google.com"> GOOGLE LINK </a>

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

Javascript function interacts with other function

I am completely new to javascript (and jquery) and have been experimenting with drop down menus the past couple of days. I found this one fancy notification menu, and I tried to see what happens when I have two of them on the page. Anyways, I made a quick example of my problem here:
http://jsfiddle.net/rgt03mu4/24/
The problem is that I can have both notification containers open up if I click on both.
If I am already clicked on one of the bells, then I click on the other, it should close the other one. Instead it keeps it open, and even when you click on the other container one, it still doesn't close it. You have to click off the page or click the notification bells. I am trying to make it to where you can only have one open at a time. So in order to do this, I tried changing the names of the functions:
As you can see:
$(function() {
var nContainer = $(".notification-popup-container");
//notification popup
$("#notification-link").click(function() {
nContainer.fadeToggle(300);
return false;
});
//page click to hide the popup
$(document).click(function() {
nContainer.hide();
});
//popup notification bubble on click
nContainer.click(function() {
return false;
});
});
I added the next function to be called test(), which you would think, since it's an entirely new function it would work differently. Instead, the error still persists.
What am I doing wrong? I even gave the the new bell it's own divs and link name. I also renamed container to container2.
Set the global variable for your container:
var nContainer = $(".notification-popup-container");
var nContainer2 = $(".notification2-popup-container");
$(function() {
var nContainer = $(".notification-popup-container");
//notification popup
$("#notification-link").click(function() {
nContainer.fadeToggle(300);
nContainer2.hide(); //hide the second container
return false;
});
//page click to hide the popup
$(document).click(function() {
nContainer.hide();
});
//popup notification bubble on click
nContainer.click(function() {
return false;
});
});
And you can do same with other function.
DEMO
There is no need to give the popup containers different classnames.
I would give the a-tags a common classname instead of an id. The href can be used to identify the target popup, so the binding between the link and the target popup is set in the origin of action. The JS part would be abstracted and could be reused.
<a class='notification-link' href='#firstpopup'>X</a>
<a class='notification-link' href='#secondpopup'>X</a>
<div class='notification-popup-container' id="firstpopup">
... firstpopup
</div>
<div class='notification-popup-container' id="secondpopup">
... secondpopup
</div>
The click handler first hides all the popups before opening a new one.
$(".notification-link").click(function () {
$(".notification-popup-container").hide();
var targetId = $(this).attr('href');
$(targetId).fadeIn(300);
return false;
})
working example: http://jsfiddle.net/qyLekdwk/
The problem here is how the event propgation is handled
$(function () {
var nContainer = $(".notification-popup-container");
//notification popup
$("#notification-link").click(function () {
nContainer.fadeToggle(300);
});
//page click to hide the popup
$(document).click(function (e) {
if (!$(e.target).closest('#notification-link, .notification-popup-container').length) {
nContainer.hide();
}
});
});
$(function test() {
var nContainer2 = $(".notification2-popup-container");
//notification popup
$("#notification2-link").click(function test() {
nContainer2.fadeToggle(300);
});
$(document).click(function (e) {
if (!$(e.target).closest('#notification2-link, .notification-popup-container').length) {
nContainer2.hide();
}
});
});
Demo: Fiddle

Double click prevented but prevent default does not work

I am using code from this post and the double click prevention works, however the button still does not respond to preventDefault
Can anyone lend a hand please?
js:
var myBtn = $('.myLink');
var handler = function(e){
e.preventDefault();
console.log("prevent 2x click");
$(this).unbind('click');
setTimeout(function(){ myBtn.click(handler); }, 500);
}
myBtn.click(handler);
html:
<a class='myLink' href="#">my link to click</a>
Reason is that when you unbind the handler(which has preventDefault) and in the small period of time one more click comes in it doesn't prevent the default behavior. So you can attach a dedicated handler to prevent default and unbind the handler that just does your other logic. Try this way:
var myBtn = $('.myLink');
var handler = function(e){
$(this).unbind('click', handler); //unbind only your handler
setTimeout(function(){
myBtn.click(handler); }
, 500);
}
myBtn.click(preventDefault); //have this bound to the anchor to prevent the default behavior always
myBtn.click(handler);
function preventDefault(e){
e.preventDefault();
}
Demo

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');
});
​

select the Div without specific content

Q:
I have the following case :
Div contains a link , i wanna to just select the div without the link,i mean ,when clicking on the div i wanna specific action differs from clicking the link.through some JQuery.
the structure i work on is:(by firebug)
<div class ="rsAptContent">
sql
<a class = "rsAptDelete" href = "#" style ="visibility: hidden;">Delete</a>
</div>
the JQuery code:
<script type="text/javascript">
$(document).ready(function() {
$(".rsAptContent").click(function(e) {
ShowDialog(true);
e.preventDefault();
});
});
function ShowDialog(modal) {
$("#overlay").show();
$("#dialog").fadeIn(300);
if (modal) {
$("#overlay").unbind("click");
}
else {
$("#overlay").click(function(e) {
HideDialog();
});
}
}
function HideDialog() {
$("#overlay").hide();
$("#dialog").fadeOut(300);
}
</script>`
when i click on the link ,i don't want to execute the Jquery code , how to select the div without the link in.
thanks in advance
Are you looking for something like the stopPropagation() code?
$(".rsAptContent").click(function(e) {
e.stopPropagation();
ShowDialog(true);
return false;
});
});
That should stop the link from executing.
http://api.jquery.com/event.stopPropagation/
Edit: Distinguish between clicking the link and clicking on any part of the content except the link
$(".rsAptContent").click(function(e) {
var $target = $(e.target);
if($target.is(a){
// It's the link.
}else{
// else it's not
}
});
});
Check for the clicked target element than perform action
to get info about which element is click use below script
function whichElement(event){
var tname
tname=event.srcElement.tagName
alert("You clicked on a " + tname + " element.")
}
Try this:
$(".rsAptContent").click(function(e) {
if($(e.target).hasClass('rsAptDelete')) return false;
ShowDialog(true);
e.preventDefault();
});
});
If the target is the link the event is cancelled;
If you already have a click handler on the delete link, then just stop the event propagation there by using stopPropagation().
$(".rsAptDelete").click(function(e) {
e.stopPropagation();
});

Categories

Resources