Applying a function to all buttons? - javascript

Im working on a quick script to apply an alert and redirect message to all anchors and buttons on a page. So far, I have this working for all anchors:
document.querySelector('body')
.addEventListener('click', function (event) {
if
(event.target.tagName === 'A' || event.target.tagName === 'button') {
event.preventDefault();
alert("test");
window.open('http://www.test.com', '_self');
}
});
When i try to apply the same idea to all buttons (see after the || in the script), it does not apply. Am I missing something?

event.target.tagName results are capitalized.
A BUTTON TEXTAREA etc.

Related

How can I use javascript to disable all links on page except those with a particular class

sorry I am new to javascript but i'm working on a wordpress website and have to disable all the links on the home page from being clickable except the links with a particular class e.g. 'clickable'. As long as the link has that class, it becomes clickable.
I have been tweeking the below script but do not know how to introduce the class comparism, can anyone help me with this?
var links = document.getElementsByTagName('a');
document.addEventListener('click', function (e) {
if (e.target.tag === links.tag) {
e.preventDefault();
document.addEventListener('contextmenu',
event => event.preventDefault());
el_down.innerHTML = "Right click disabled";
}
});
This did it:
document.body.addEventListener('click', function (event) {
// filter out clicks on any other elements
if (event.target.nodeName == 'A' && event.target.getAttribute('aria-disabled') == 'true') {
console.log("True")
}
else {
event.preventDefault();
document.addEventListener('contextmenu',
event => event.preventDefault());
el_down.innerHTML = "Right click disabled";
}
});

External Link Notification - JavaScript or JQuery

I am looking for a way to set it up so that when an external link is clicked it will warn people that they are leaving the site. Preferably, it would darken the screen and display a message in the middle of the screen in a box with the option to click OK or Cancel.
I tried to use this code:
$("a.external").click(function () {
alert("You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.");
});
and give each link a class of external but it doesn't seem to work. I don't want to use this because it means that the client will have to remember to add the class I would prefer something more automatic.
I also tried to use this code to do so but to no avail:
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
var x=window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
var val = false;
if (x)
val = true;
else
val = false;
return val;
});
I am using WordPress 3.8.1.
Thanks in advance for any help you can give.
Your filter logic should be correct, Try using the confirm function, and using jQuery instead of $.
jQuery('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).click(function(e) {
if(!confirm("You are about to proceed to an external website."))
{
// if user clicks 'no' then dont proceed to link.
e.preventDefault();
};
});
I tried this out in dev tools on your site and it seems to work correctly if you use jQuery. I think you may have some plugin that is causing conflicts with $.
JSFiddle Demo
Try using confirm instead of alert since that will pause and wait for user input. You'll then need function(e){ e.preventDefault(); } to prevent the default link actions.
To identify just external links you might do something like this:
var ignoreClick = false;
$(document).ready( function(){
$('input[type="submit"], input[type="image"], input[type="button"], button').click(function(e) {
ignoreClick = true;
});
$(document).click(function(e) {
if($(e.target).is('a'))
checkLink(e);
});
$('a').click(function(e) {
checkLink(e);
return true;
});
checkLink = function(e){
// bubble click up to anchor tag
tempTarget = e.target;
while (!$(tempTarget).is('a') && !!tempTarget.parentElement) {
tempTarget = tempTarget.parentElement;
}
if ($(tempTarget).is('a')){
if(!!tempTarget && $(tempTarget).is('a') &&
(tempTarget.hostname == "" || tempTarget.hostname == "#" || tempTarget.hostname == location.hostname)){
ignoreClick = true;
}
}
}
});
and to catch people with a message you might use beforeunload and the confirm option
$(window).bind("beforeunload", function (e) {
if (!ignoreClick){
if(!confirm("Leaving website message")) {
e.preventDefault();
}
}
});
It worked pretty well to me. I just removed unnecesary variables, but original script worked fine.
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
return window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
});
http://jsfiddle.net/3dkAN/1/
EDIT
Following #user1308743's line, seems that in cgmp.framework.min.js is summoning the jQuery.noConflict() mode, that unbinds the $() function for jQuery. So please use jQuery() for any jQuery implementation

JQuery: Click anywhere other than #element

Nothing in the recommended questions covers it. I'm trying to initiate an event if a click occurs anywhere in the document other than in one of two specific divs. This is what I'm doing:
$('html:not(#optionsDropdown):not(#settingsButton)').click(function() {
if ($('#settingsCogCheck').val() === '1') {
alert('click');
}
});
It isn't working, though. Any clue as to why?
Thanks!
You can't add a listener to "everything except x", but you can listen on document, and check the element inside the click handler:
$(document).click(function() {
var id = $(this).id;
if (id != 'optionsDropdown' && id != 'settingsButton') {
if ($('#settingsCogCheck').val() === '1') {
alert('click');
}
}
});

jQuery separate dblclick events inside and outside of a div element

I'm developing a local site for content creation, and I'd like to use javascript's double click functionality.
I'd like to rotate through full screen background images when the user double clicks outside of the divs with names/ids bigwrapper or bigwrapper2. When the user clicks #bigwrapper or #bigwrapper2, I'd like it to .toggle(); each one to hide/show one or the other.
Here's my updated code (thanks lordvlad):
$(function() {
$( "#bigwrapper" ).draggable();
$( "#bigwrapper2" ).draggable();
var SacramentoBG = ['nightcap.jpg','Tower_Bridge_Sacramento_edit.jpg'],
counter =0;
$('html').dblclick(function (event) {
if (event.target.id != "bigwrapper" && event.target.id != "bigwrapper2") {
counter = (counter+1) % SacramentoBG.length;
$('html').css('background-image', "url("+SacramentoBG[counter]+")");
} else {
$("#bigwrapper").toggle();
$("#bigwrapper2").toggle();
}
});
});
UPDATE: The solution below to add 'event' inside the function partially helped, as the backgrounds rotate properly, however the #bigwrappers aren't toggling as intended (the else condition). See: http://artfuladvection.com/project/NOAA/ndfdGraph/bloom.php Ideas?
Thanks!
that's because the dblclick function doesn't know about the event variable. try this
$('html').dblclick(function (event) {
The complete answer that worked for me was that I needed to stop excluding specific classnames/ids and instead exclude entire element tags. Alternatively, I could just use if (event.target.TagName == 'BODY') {}
$('body').dblclick(function (event) {
if (event.target.tagName != 'DIV' && event.target.tagName != 'IMG' && event.target.tagName != 'TABLE' && event.target.tagName != 'HR' && event.target.tagName != 'SMALL' ) {
counter = (counter+1) % SacramentoBG.length;
$('html').css('background-image', "url("+SacramentoBG[counter]+")");
} else {
$("#bigwrapper").toggle();
$("#bigwrapper2").toggle();
}
});

only writing "return false" once to handle clicking on many links

Instead of writing return false; many times is there a way to set a collection of links such that if any of them are clicked the click function would return false;? I'd still like to have most links return true so showing code that would return true vs. return false would be particularly appreciated.
The goal is writing less code. I'd also like to know if this is a bad idea for reason I can't understand.
The simpliest method is binding one event listener to the document, and checking for the target: http://jsfiddle.net/gKZ7q/
document.addEventListener('click', function(e) {
if (e.target.nodeName.toUpperCase() === 'A') e.preventDefault();
}, false);
For anchors with nested elements, you have to add an additional loop:
var targ = e.target;
do {
if (targ.nodeName.toUpperCase() === 'A') {
e.preventDefault();
break;
}
} while ((targ = targ.parentNode) !== document.documentElement);
// document.body should be fine. Using document.documentElement in case
// that a fool places an anchor outside the <body>
Links can also be triggered through a key event.

Categories