in the below code, I am fading out any page, and then fading in the new page, when any tag is clicked. However, there are certain instances where we don't want to fade the page out on click, for example, when an tag is set to open externally via target="_blank". The code below reflects this and is working successfully.
However, one thing I'm not sure how to achieve, is to prevent the fade out when a link contains a mailto: reference, as obviously this is designed to open a mailing client window. Therefore I don't want the page to fade out?
Thank you.
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload();
}
});
(function($) {
if (window.history) {
$(window).on('popstate', function() {
$("body").show();
});
}
// When links are clicked
$(document).on("click", "a", function() {
var $link = $(this);
var $href = $link.attr("href");
var $target = $link.attr("target");
// If link exists
if ($href) {
// Fade out all links unless set to open in external window target="_blank"
if ($target !== "_blank") {
$("body").fadeOut(250, function() {
history.pushState($href, null, null);
window.location.href = $href;
});
return false;
}
}
});
// On page load, fade in
$(document).ready(function() {
$("body").fadeTo(250, 1);
});
}(window.jQuery));
a very elegant way to do this is to use the awesome power of the css attribute selector and pass the validation so you only need this:
$(document).on('click','a[href]:not([href^=mailto],[target="_blank"])',function(){
$("body").fadeOut(250, function() {
history.pushState(this.href, null, null);
window.location.href = this.href;
});
return false;
})
this is where the "magic" happens: a[href]:not([href^=mailto],[target="_blank"]) (UPDATED to include the "has href" clause
I only select links that the href does not start with mailto and do not have target="_blank"
more on attribute selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
Simply check the link url:
if($href.indexOf('mailto:') === 0){
//the url starts with mailto:
//it is an email link
}
More specific to your usecase, extend the if statement where you check for _blank:
if ($target !== "_blank" && $href.indexOf('mailto:') !== 0) {
//...
}
For a link that contains a mailto: reference just change this part in your code
if ($href) {
with this
if ($href && $href.indexOf('mailto:')!==-1) {
Alternatively check this fiddle demonstrating the usage of :not. In your case don't forget to use event.preventDefault() for the mailto links from opening mail client window.
Related
I want to add a class 'hidden' to a div once the user has clicked to close it. My code below sets a cookie for 7 days so I want that class to be active for that time. Is this poss? Hoping it's an easy fix
My JS:
jQuery(document).ready(function(){
// if the cookie exist, hide the element
var hide = Cookies.getJSON('hide');
if (hide && hide.element)
$(hide.element).hide();
$('#hideshow').on('click', function(event) {
$('.following_prompt').addClass('hidden');
$('.following_prompt').hide();
Cookies.set('hide', {element: '.following_prompt'}, { expires: 7 });
return false;
});
});
You don't have to use a class. You could use .is(':visible') but I created the example so that you can see what the code would look like to add/remove a class.
jQuery(document).ready(function(){
$('#hideshow').on('click', function(event) {
var $following_prompt = $('.following_prompt');
if($following_prompt.is(":visible"))
$following_prompt.addClass('hidden').hide();
else
$following_prompt.removeClass('hidden').show();
event.preventDefault();
});
});
https://jsfiddle.net/5g67btrL/
You can use a helper class like: Small Cookies JavaScript Helper.
Download js file in https://raw.githubusercontent.com/tdd/cookies-js-helper/master/src/cookies.js to local.
Include path in your HTML file to load Small Cookies JavaScript Helper.
Example of use:
jQuery(document).ready(function(){
// if the cookie exist, hide the element
var hide = Cookie.get('hide');
if (hide !== '')
$(hide).hide();
$('#hideshow').on('click', function(event) {
$('.following_prompt').addClass('hidden');
$('.following_prompt').hide();
Cookie.set('hide', '.following_prompt', { maxAge: 7*(3600*24) });
return false;
});
});
Is it possible to assign url to the an anchor only when it got clicked?
Token Link
When the anchor got clicked, it will go to http://example.com/token=xxxxx/
I want to generate token only when it got clicked.
If possible, How?
thanks
you can handle the event and change the href like this.
$("a").on("click", function() {
$(this).attr("href", $(this).attr("href") + "/token=xxxx");
});
you can also directly navigate the user to a different url, without changing.
$("a").on("click", function(ev) {
document.location.href = "//something-different.com";
ev.preventDefault();
return false;
});
Opening the link in another window using jQuery
$(document).ready(function () {
$(".thisClass a").on("click", function(e){
e.preventDefault(); // this prevents going to the original url or default behavior
var changedLink = $(this).attr("href", $(this).attr("href") + "/token=xxxx");
var newUrl = $(changedLink).attr('href');
window.open(newUrl, '_blank');
});
});
// Here is a way to do it with Plain Javascript - i did not test it on all browsers but worked with chrome for example.
// goes in a script.js or in script tags under the </body> element
function changeTheLink() {
event.preventDefault();
var aLink = document.getElementById('theLink');
var theOldLink = aLink.getAttribute("href");
aLink.setAttribute('href', theOldLink + "/token=xxxx");
var theNewLink = aLink.getAttribute("href");
window.open(theNewLink, "_blank");
}
// here is the HTML you owuld have to add an id and an onclick attribute to use this code
<div class="thisClass"><a href="http://thiswebsite.com" id="theLink"
onclick="changeTheLink()">Here is a link</a></div>
I'm currently using the following code to allow a user to show/hide a div on click.
When clicking anywhere outside of the div, it closes the div.
However, there is a link within the div which can open a lightbox. When a user goes to close that lightbox, it also closes the div that the link was contained. Is there anything I can add into the script to stop that from happening?
$(document).ready(function(){
$("a.dropdown-link").click(function(evt) {
evt.preventDefault();
var $div = $(this).next('.info-container');
$(".info-container").not($div).slideUp();
if ($div.is(":visible")) {
$div.slideUp()
} else {
$div.slideDown();
}
});
$(document).click(function(e){
var p = $(e.target).closest('.dropdown').length
if (!p) {
$(".info-container").slideUp();
}
});
$('.movie-link').magnificPopup({type:'iframe'});
});
<a class="dropdown-link" href="#"><div class="dropdown dropdown-processed">More info</div></a>
<div class="info-container" style="display: none;">Video preview: <a class="movie-link" href="videourl"></a></div>
I'm using Magnific Popup for the lightbox: http://dimsemenov.com/plugins/magnific-popup/
My JavaScript knowledge is pretty basic so any help is appreciated.
In the "click to close div function, you can check if the lightbox is on or not. A simple if ($("#lightbox").css("display") == "none") should be able to do the trick
EDIT: put this line after the $(document).ready line
var state = 0; // default state
$('.movie-link').click(function() { state = 1; }); // state = 1, lightbox on
in the source code, on line 384, insert this code
state = 2; //state = 2, lightbox close button clicked
the idea is not firing the "close div" function when the state is 1 (lightbox is on and clicking random stuffs inside, or outside the lightbox) or 2 (lightbox's close button got clicked), and return state to 0 when it was 2
so instead of the if I provided in the comment use this
if (state == 2) {
state = 0;
} else if (state == 0) {
//rest of the code
}
this is just something I put together and haven't tested yet, so I don't actually know if it works or not so just back up your js files just in case.
EDIT 2:
remove all the changes in edit 1 and use this on instead of the if (state == 2) {
if (e.target != $('.mfp-bg')[0] and e.target != $('.mfp-wrap')[0]) {
EDIT 3
var e_class = $(e.target).attr('class');
if (e_class != 'mfp-close' && e_class != 'mfp-container') {
working example: http://imgcrash.comeze.com/test.html
I'm not 100% without actually testing this out but you may be running into issues with $(document).click(...); since clicking anywhere on the document would trigger this event.
When you close the popup you're probably triggering this event and sliding up the info-container div.
It seems that you're looking for clicks on the divs with the class .dropdown. Why not use something like:
$('.dropdown').click(function(e) { ... });
Try this:
$("a.dropdown-link").click(function(evt) {
evt.preventDefault();
evt.stopPropagation(); //We stop the propagation of the event
//Changed it to slideToggle and added stop to prevent weird animation
//on multiple clicks
$(this).next('.info-container').stop().slideToggle()
});
$(document).click(function(e){
//Check if it has the class info-container
if (!$(e.target).hasClass("info-container")) {
$(".info-container").slideUp();
}
});
$('.movie-link').magnificPopup({type:'iframe'});
Fiddle
I'm capturing all the clicks in my "a" elements with this:
$("a").click(function(e){....});
I want to know if it's possible to discard some events depending on some variable.
For example..
If href="http://www.google.es" then alert("google.es")
else if href="http://www.google.com" then do not handle the event and let the browser do whatever it has to do.
I don't know if I've explained it very well...
Or, you could do:
$("a[href!='http://www.google.com']").click(function(e) {
e.preventDefault();
if(this.getAttribute('href') === 'http://www.google.es') alert("google.es");
});
And not generate the click event for google.com in the first place.
$("a").click(function(e){
e.preventDefault();
if (this.href == "http://www.google.es/") alert("google.es");
else if (this.href == "http://www.google.com/") window.location = this.href;
});
Fiddle Demo: http://jsfiddle.net/maniator/5XdkV/
Inside your function $(this).attr('href') should give you the href of the anchor tag - which you can then use in the rest of your logic
For your example above,
$('a[href*=.es]').click(function(e){
e.preventDefault();
});
Would make all links that contain .es in the href attribute to not be followed, but leaves the other links alone.
$("a").click(function(e) {
if ($(this).attr('href') == 'http://www.google.es') {
alert('google.es');
e.preventDefault();
}
// if code gets here, it's ok for the browser to handle normally.
}
All the suggestions posted so far will work, but they aren't the most flexible. If you want to match any link that has google.es as the hostname, I'd do something like this:
$(document.body).delegate('a', 'click', function(e) {
var hostname = this.hostname || $(this).prop('href').split('/')[1];
if (hostname == 'www.google.es') {
alert('google.es');
e.preventDefault();
}
});
how can i select the current link via jquery if I have a div like this:
<div id='navigation'>
<a href='users/home'>home</a> |
<a href='projects/browse'>home</a>
<a href='discussions/browse'>home</a>
<a href='search/dosearch'>home</a>
</div>
Note I've tried:
$(document).ready(function(){
$("#navigation a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
clicked.addClass('selected');
});
});
But when I click on a link it selects a link and adds the class .selected but it reloads the page in order to navigate to a page and then it all disappears. Any tips?
Thanks
This should work:
$(document).ready(function() {
var loc = window.location.href; // The URL of the page we're looking at
$('#navigation a').each(function() {
if (loc.indexOf(this.href) !== -1) { // If the URL contains the href of the anchor
$(this).addClass('selected'); // Mark it as selected
}
});
});
It basically loops over the navigation items, and if the URL of the current page contains the href of the anchor, it adds the class selected to the anchor.
Yep, take the event from your click() callback arguments and use e.preventDefault(); (see there).
Or return false.
Or add a target='_blank' attribute to your links so that they open the link in some other page or tab, if you still want the link to be opened by the browser somewhere.
$(document).ready(function(){
$("#navigation a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
clicked.addClass('selected');
return false;
});
});
Don't forget to return false!