External Link Notification - JavaScript or JQuery - javascript

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

Related

How to synchronise ExtJS "checkboxes" (buttons) with Javascript/JQuery?

I am currently trying to synchronize two checkboxes on a page.
I need the checkboxes to be synchronized - to this end, I'm using a Tampermonkey userscript to pick up when one of them is clicked. However, I'm at a loss as to how to do it.
I believe they are not actually checkboxes, but ExtJS buttons that resemble checkboxes. I can't check whether they're checked with JQuery because of this: the checked value is appended to a class once the JS behind the button has run.
I have tried preventDefault and stopPropagation, but either I'm using it wrong or not understanding its' usage.
I'm not quite clever enough to just call the JS behind the box instead of an onclick event. Otherwise, that would solve my issue.
This is my code:
//Variables - "inputEl" is the actual button.
var srcFFR = "checkbox-1097";
var destFFR = "checkbox-1134";
var srcFFRb = "checkbox-1097-inputEl";
var destFFRb = "checkbox-1134-inputEl";
//This checks if they're synchronised on page load and syncs them with no user intervention.
var srcChk = document.getElementById(srcFFR).classList.contains('x-form-cb-checked');
var destChk = document.getElementById(destFFR).classList.contains('x-form-cb-checked');
if (srcChk == true || destChk == false) {
document.getElementById(destFFRb).click();
} else if (destChk == true || srcChk == false) {
document.getElementById(srcFFRb).click();
}
//This is where it listens for the click and attempts to synchronize the buttons.
$(document.getElementById(srcFFRb)).on('click', function(e) {
e.preventDefault();
if (document.getElementById(srcFFR).classList == document.getElementById(destFFR).classList) {
return false;
} else {
document.getElementById(destFFRb).click();
}
});
$(document.getElementById(destFFRb)).on('click', function(e) {
e.preventDefault();
if (document.getElementById(srcFFR).classList == document.getElementById(destFFR).classList) {
return false;
} else {
document.getElementById(srcFFRb).click();
}
});
I'm at a bit of a loss...any help would be greatly appreciated.
Figured it out - I was comparing class lists without singling out what I wanted to actually match.
My solution:
$(document.getElementById(srcFFRb)).on('click', function(){
if (document.getElementById(srcFFR).classList.contains('x-form-cb-checked')
== document.getElementById(destFFR).classList.contains('x-form-cb-checked')) {
return false;}
else {
document.getElementById(destFFRb).click();;
}});
$(document.getElementById(destFFRb)).on('click', function(){
if (document.getElementById(srcFFR).classList.contains('x-form-cb-checked')
== document.getElementById(destFFR).classList.contains('x-form-cb-checked')) {
return false;}
else {
document.getElementById(srcFFRb).click();;
}});

Leaving Website Notification

I have this jQuery script that alerts the user when they're exiting to a third party website. Works fine when you just click on it, but if the user ctrl+clicks or right click > open new tab the warning message doesn't display. How can I amend this code to have the notification appear regardless of how the user clicks/opens the link?
// notification when exiting to third party website
jQuery('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).click(function(e) {
if(!confirm("You are now leaving...."))
{
// return back to page on no.
e.preventDefault();
};
});
This is a Credit Union regulation, so I'm not a butthead for doing so.
The right click that is context menu is a browser feature. You have to either disable it completely or create your own context menu using HTML.
Here is an answer to address the issue of ctrl+click.
If the key is pressed and if it is the ctrl key, just add e.preventDefault()
$(document).keydown(function (e) {
if(e.which==17)
e.preventDefault();
});
jQuery('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).click(function(e) {
if(!confirm("You are now leaving...."))
{
e.preventDefault();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
G

stop redirecting page if it is redirecting by clicking on anchor

I want to prevent page redirecting I know it can be achieve by this
window.onbeforeunload = function() {
return "Dude, are you sure you want to leave? Think of the kittens!";
}
which was answered here Prevent any form of page refresh using jQuery/Javascript
But in my case I only want to prevent page when it is redirecting by clicking on any of the anchor tag.
Also event.preventDefault() will not work in my case while clicking on anchor tag because all anchors are not redirecting page so it should work fine.
I only want to stop redirecting page if it is redirecting by clicking on anchor. Any solution?
You can keep a flag which tells you whether or not the user clicked an a tag, then read that on your onbeforeunload script:
window.onbeforeunload = function () {
if (_clickedAnchor) {
_clickedAnchor = false;
return "Dude, are you sure you want to leave? Think of the kittens!";
}
}
_clickedAnchor = false;
jQuery(document).ready(function () {
jQuery("a").click(function () {
_clickedAnchor = true;
});
});
You can use onhashchange.
With jQuery:
$(window).on('hashchange', function() {
alert('bye byee?');
});
Plain DOM JavaScript:
window.onhashchange = function() {
alert('bye byee?');
};
Note: You will need to create a custom "hash-change" handler for older browser which don't support this event.
You can easly do this with setInterval and detect any changes in document.location.hash.
Failsafe onhashchange for older browsers:
var currentHash = document.location.hash;
window.prototype.onhashchange = function( callback ) {
if(typeof(callback) == 'function') {
setInterval(function() {
if(document.location.hash !== currentHash) {
callback();
}
}, 650); // more than a half-a-second delay
}
}
And you can use it as an event in regular DOM convention.
So since you tagged jQuery I'll put my solution in terms of that. You can grab all the a tags and then check to make sure the anchor is a redirect, then use the e.preventDefault();
$('a').on('click',function(e){
if ($(this).attr('href') != window.location.href)
{
e.preventDefault();
//do stuff
}
});
The caller will be null if a link is clicked:
window.onbeforeunload = function() {
alert(window.onbeforeunload.caller)
}

Problem with event.target in IE

I'm writing js for a status update system to be used on various pages throughout a app that I'm working. I am really just starting to get more comfortable with javascript so it has been somewhat of a challenge to get to the point where I have everything now.
The status system is basically a facebook clone. For the most part everything is supposed to function the way that facebook's status updates and status comments do. The intended behavior is that when the user clicks in the status textarea, the div under the status textarea slides out revealing the submit button as well as some other checkboxes.
If the user clicks anywhere else on the page except a link or any element that has the class prevent_slideup the div slides up hiding the submit button and any checkboxes.
I'm using a document.body click function to determine what the user clicked on so I know which form elements to hide if I should even hide them. I do not want this slideup to take place on a textarea if that textarea has focus or the user is selecting a checkbox that goes with that form. Hence the prevent_slideup class. I also do not want to bother running the slideup logic if the user has clicked on a link. I'd prefer they just leave the page without having to wait for the animation.
The code that I was using to accomplish this task can be found in the $(document.body).click(function (e) section below where I'm doing a .is('a') check on the event target.
This code works as expected in chrome and firefox, however in ie when a link is clicked for the first time it seems that the element stored in var target is actually a div instead of an anchor. What ends up happening is that the submit div slides up and the user is not taken to the link that they just clicked on. If a link is clicked a second time the user is taken to the page as you would expect.
It seems to me that there's some kind of a lag in ie as to what the current event being fired is.
The entire status module is working other than this one strange ie bug regarding the users click on the link not being carried out the first time that they click a link after opening the status textarea. Does anything jump out in this script that would explain this behavior or does anyone have any other advice?
Thanks in advance for your help.
$(document).ready(function(){
$("textarea.autoresize").autoResize();
});
$(document.body).click(function (e){
var target = e.target || e.srcElement;
console.log(target);
console.log($(target).is('a'));
if($(target).hasClass('prevent_slideup') || $(target).is('a'))
{
return true;
}
else
{
var active_element = document.activeElement;
var active_status_id = $(active_element).attr('data-status_id');
var active_has_data_status_id = (typeof active_status_id !== 'undefined' && active_status_id !== false) ? true : false;
$('textarea').each(function(){
if($(this).hasClass('status_comment_textarea'))
{
var status_id = $(this).attr('data-status_id');
if($('#comment_textarea_'+status_id).val() === '' && (!active_has_data_status_id || active_status_id !== status_id))
{
hide_status_comment_submit(status_id);
}
}
else if($(this).attr('id') === 'status_textarea')
{
if($('#status_textarea').val() === '' && $(active_element).attr('id') !== 'status_textarea')
{
$('#status_textarea').html($("#status_textarea").attr('placeholder'));
hide_status_submit();
}
}
});
return true;
}
});
$("#status_textarea").live('click', function(){
if($('#status_textarea').val() === $("#status_textarea").attr('placeholder'))
{
$('#status_textarea').html('');
}
show_status_submit();
return false;
});
$(".comment_toggle").live('click', function(){
var status_id = $(this).attr('data-status_id');
show_status_comment_submit(status_id);
return false;
});
$(".status_comment_submit").live('click', function(){
var status_id = $(this).attr('data-status_id');
$('#status_comment_submit_wrapper_'+status_id).addClass('status_comment_submit_successful');
return false;
});
$(".show_hidden_comments").live('click', function(){
var status_id = $(this).attr('data-status_id');
$('#status_hidden_comments_'+status_id).show();
$(this).hide();
return false;
});
function hide_status_submit()
{
$("#status_textarea").removeAttr('style');
$("#status_textarea").blur();
$("#status_block").removeClass('padding_b10');
$("#status_submit_wrapper").slideUp("fast");
return false;
}
function show_status_submit()
{
if ($("#status_submit_wrapper").is(":hidden"))
{
$("#status_block").addClass('padding_b10');
$("#status_submit_wrapper").slideDown('fast');
}
return false;
}
function hide_status_comment_submit(status_id)
{
if(!$('#status_comment_submit_wrapper_'+status_id).is(":hidden"))
{
$('#status_comment_submit_wrapper_'+status_id).hide();
$('#fake_comment_input_'+status_id).show();
$('#comment_textarea_'+status_id).removeAttr('style');
}
return false;
}
function show_status_comment_submit(status_id)
{
if($('#status_comment_submit_wrapper_'+status_id).is(":hidden"))
{
$('#fake_comment_input_'+status_id).hide();
$('#status_comment_submit_wrapper_'+status_id).show();
$('#comment_textarea_'+status_id).focus();
}
return false;
}
function status_comment_submit_successful()
{
hide_status_comment_submit($('.status_comment_submit_successful').attr('data-status_id'));
$('.status_comment_submit_successful').removeClass('status_comment_submit_successful');
return false;
}
I figured out that there were two main issues with my script...
1.) The document.body function and the #status_textarea live click funtioins were conflicting with each other.
2.) After adding the logic for the #status_textarea function into the document.body function I noticed that the script still didn't quite work as expected in internet explorer unless I had an alert in the function. The problem at this point was that the autoresize plugin that I'm using on the textarea was also conflicting with the document.body function.
I was able to rectify the situation by adding a dummy text input and hiding the status textarea. On click of the dummy text input the status textarea is shown and the the dummy text input is hidden. I have no idea why this worked, but it seems to have solved my problems.

how to open outside links in a new tab

On my website i have many outside links, as well as internal links.
i'd like some kind of solution in javascript or w/e that detects outside links and opens them in a new tab, but leaves internal links to be opened in the same tab.
thanks! =)
function getXterlinks()
{
var Xterlinks = document.getElementsByTagName('A');
for (var i=0;i<Xterlinks.length;i++)
{
var eachLink = Xterlinks[i];
var regexp_isYourdomain="your-domain.com";
var regexp_ishttp=/(http(.)*:\/\/)/;
if( (eachLink.href != null) && (eachLink.href.match(regexp_isYourdomain) == null) && eachLink.href.match(regexp_ishttp)!=null )
{
eachLink.target ="_blank";
}
}
}
Source: http://www.mediawiki.org/wiki/Manual:Opening_external_links_in_a_new_window#How_to_make_external_links_open_in_a_new_window
Yeah, well, jQuery's still JavaScript. How about:
$('a[href^="http://your-domain.com"]').attr("target", "_self");
$('a').not('a[href^="http://your-domain.com"]').attr("target", "_blank");
Not sure about the second, though, but you get the idea.
I wrote this solution for my personal web site. As long as you like jQuery (which you should, imho), you can include this in a common js file and forget about it. It will work with dynamic content, and will not force internal links to open in the current tab if you set target="_blank".
$(function() {
$('body').on('click', 'a', function() {
var currentHost = document.location.protocol+'//'+document.location.hostname;
if (this.href.indexOf(currentHost) != 0 && (this.href.indexOf('http') == 0 || this.href.indexOf('ftp') == 0)) {
window.open(this.href, '_blank');
return false;
}
});
});
Note: If you are using jQuery < 7, use .bind() instead of .on()
See it in action on http://www.seanknutson.com.

Categories