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();
}
});
Related
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.
The User should be able to change the Name and then confirm the change. I'm not able to archive it with this code as when I click confirm, it returns like before.
What am I missing?
Any better way to put this together (which I'm sure there's one) ?
Please check the demo where you can also see the changeElementTypefunction
http://jsfiddle.net/dLk6E/
js:
$('.replace').on('click', function () {
$("h2").changeElementType("textarea");
$('.replace').hide();
$('.confirm').show();
//Confermation of the change
$('.confirm').bind('click', function () {
$('.replace').show();
$('.confirm').hide();
$("textarea").changeElementType("h2");
});
if ($('textarea:visible')) {
$(document).keypress(function (e) {
if (e.which == 13) {
alert('You pressed enter!');
$("textarea").changeElementType("h2");
$('.replace').css('opacity', '1');
}
});
}
});
Here are your updated code and working fiddle http://jsfiddle.net/dLk6E/
(function($) {
$.fn.changeElementType = function(newType) {
var attrs = {};
$.each(this[0].attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
this.replaceWith(function() {
return $("<" + newType + "/>", attrs).append($(this).contents());
});
}
})(jQuery);
$('.replace').on('click', function (){
$("h2").changeElementType("textarea");
$('.replace').hide();
$('.confirm').show();
//Confermation of the change
$('.confirm').on('click', function(){
$('.replace').show();
$('.confirm').hide();
// you are missing this
$('.replaceble').html($("textarea").val());
$("textarea").changeElementType("h2");
});
if ($('textarea:visible')){
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed enter!');
$("textarea").changeElementType("h2");
$('.replace').css('opacity','1');
}
});
}
});
updated
jsfiddle.net/dLk6E/1
I think your code is right but you need to use the value you're entering when replacing it. So the confirmation binding would be something like this (fetching it, and then using it to update the textarea before "transforming" it into an h2 tag.
$('.confirm').bind('click', function(){
var valueEntered = $('textarea').val();
$('.replace').show();
$('.confirm').hide();
$("textarea").html(valueEntered).changeElementType("h2");
});
You could be using .on for this as well as of jQuery 1.7 is prefered to .bind.
Another thing I would suggest is whenever you struggle with something like this just put in google (or whatever...) exactly what you want, in this case "jquery get value of input" will get asw first result the jquery documentation
This way you won't forget it ;)
Update: Maybe a small detail but in the binding I use it would be more efficient to just hit $('textarea') once, so it would be something like this. Something that you may keep in mind (not really an issue here), better to store in a variable than hit the DOM several times.
$('.confirm').on('click', function(){
var $textarea = $('textarea');
$('.replace').show();
$('.confirm').hide();
$textarea.html($textarea.val()).changeElementType("h2");
});
jsfiddle
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 have some simple jQuery code, and it has a problem. The menu handler function doesn't work at all.
var clicked = false;
$(document).ready(function(){
$TemplateMenu= $('<p class="paragraph">texxt</p>');
$('.TemplateMaker').click();
this.menuhandler();
});
});
function menuhandler(){
if(clicked == false){
$(this).after($TemplateMenu);
clicked = true;
}
else{
$TemplateMenu.remove();
clicked = false;
}
For some reason, the function works if I put it directly inside click() like this:
$('.TemplateMaker').click(function(){
if(clicked == false){
$(this).after($TemplateMenu);
clicked = true;
}
else{
$TemplateMenu.remove();
clicked = false;
}
});
});
What is wrong with this code? Did I define the function wrong or do I need something special if the function contain jQuery elements?
Thanks for the help :-)
Edit:
I edit the code to include your guys suggestions, its stile doesn't seem to work.
code:
var clicked = false;
$(document).ready(function(){
$TemplateMenu= $('<p class="paragraph">texxt</p><p class="p2">texxt</p>');
$('.TemplateMaker').click(menuHandler($(this)));
});
function menuHandler(obj){
if(clicked == false){
$(obj).after($TemplateMenu);
clicked = true;
}
else{
$TemplateMenu.remove();
clicked = false;
}}
I notic now that the jquery throw this "event.returnValue is deprecated. Please use the standard event.preventDefault() instead. ", but I don't know how its contact to my script.
$('.TemplateMaker').click();
this.menuhandler();
});
Try replacing this.menuhandler(); with just menuhandler(); as shown below:
$('.TemplateMaker').click();
menuhandler();
});
Edit: In response to your comment. Try using this instead of $(this) in the menuhandler() of your original code.
You probably want the menuHandler function to fire when someone clicks on the button? Then you can simply change your code as follows:
$('.TemplateMaker').click(menuHandler);
Edit:
You basically have two options:
Option1:
You don't have to pass $(this) change your code to this (make sure you remove the parameter in the menuHandler function if you choose this approach):
$(document).ready(function(){
$TemplateMenu= $('<p class="paragraph">texxt</p><p class="p2">texxt</p>');
$('.TemplateMaker').click(menuHandler);
});
Option2:
Or if you want to pass $(this) you can do something like this (keep the parameter in the menuHandler function if you choose this approach):
$(document).ready(function(){
$TemplateMenu= $('<p class="paragraph">texxt</p><p class="p2">texxt</p>');
$('.TemplateMaker').click(function() {
menuHandler($(this));
});
});
I have the following function to open an overlay menu:
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
});
To hide the menu, I would like the user to be able to click on any area outside ".context-switch-menu"
I am trying with :not() but with no success..
$('body').click(function(e) {
if ($(e.target).hasClass('context-switch')) {
return;
}
$(".context-switch-menu").hide();
});
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
return false;
});
The reason this can be difficult is because of event bubbling.
You can try something like this:
$('.context-switch').click(function(e) {
e.stopPropagation();
$(".context-switch-menu").toggle();
});
$(".context-switch-menu").click(function(e){
e.stopPropagation();
});
$("body").click(function(e){
$(".context-switch-menu").hide();
});
The e.stopPropagation() prevents the click event from bubbling to the body handlers. Without it, any click to .context-switch or .context-switch-menu would also trigger the body event handler, which you don't want, as it would nullify the effect of the .context-switch click half the time. (ie, if the state is hidden, and then you click to show, the event would bubble and trigger the body handler that would then hide the .context-switch-menu again.)
Without testing, would something like this work?:
$('.context-switch').click(function() {
$(".context-switch-menu").show();
});
$(document).click(function() {
$(".context-switch-menu").hide();
});
Instead of using document, 'html' or 'body' may work as well.
$(document).on('click', function(e) {
if (e.target.className !='context-switch-menu') {
$(".context-switch-menu").hide();
}
});
Just an idea here, based on what what others have suggested in the past:
$(document).click(function(e){
//this should give you the clicked element's id attribute
var elem = $(e.target).attr('classname');
if(elem !== 'context-switch-menu'){
$('.context-switch-menu').slideUp('slow');
//or however you want to hide it
}
});
try this, we don't want to call a function when you clicked on the element itself, and not when we click inside the element. That's why we need 2 checks.
You want to use e.target which is the element you clicked.
$("html").click(function(e){
if( !$(e.target).is(".context-switch-menu") &&
$(e.target).closest(".context-switch-menu").length == 0
)
{
alert("CLICKED OUTSIDE");
}
});
Live fiddle: http://jsfiddle.net/Xc25K/1/