Having such an html:
<a class="someclass" href="some/url/absolute/or/relative">Blah</a>
... along with such javascript:
$("a.someclass").onclick(function() {
var link = $(this).attr("href");
if (link == window.location) // <<<<<<<<<<<<
doSomethingSpecial();
else
doOtherThing();
return false;
});
this code obviously doesn't work.
How to reliably detect that some anchor is leading to the current browser location?
Here are some notes:
Anchor's href could be either absolute or relative.
the fragments of the URLs should be ignored.
The problem is that $('a').attr('href') always returns the relative path. You need to use the native obj.href attribute to get the absolute path, strip hashes and then compare:
var clean = function(str) {
return str.replace(/(\#.*)/,'').toLowerCase();
}
$("a.someclass").click(function(e) {
if (clean(this.href) == clean(window.location)) {
// the link destination is equal to window.location (excluding hashes)
doSomethingSpecial();
} else {
doOtherThing();
}
e.preventDefault();
});
EDIT:
If you want to compare pathnames, you can grab it directly from the anchor element:
$("a.someclass").click(function(e) {
if (this.pathname == window.location.pathnname) {
doSomethingSpecial();
} else {
doOtherThing();
}
e.preventDefault();
});
AFAIK, you cannot detect that. Because I can write onclick event handler and then write the code that leads to the current location itself. In this case you can't really depend n the href attribute.
function ReloadWin()
{
window.location.reload();
}
Click me to reload
try this:
$(document).ready(function(){
$("a.someclass").click(function(){
//convert both to lower case
var h=$(this).attr("href").toLowerCase();
var l=window.location.href.toLowerCase();
//if has hash tag remove portion after if
if(l.indexOf("?")>0)
l=l.substring(0,l.indexOf("?"));
if(l.indexOf("#")>0)
l=l.substring(0,l.indexOf("#"));
if(l.length > h.length)
l = l.substring(l.length - h.length);
if(l==h){
alert("On same page");
}else{
alert("Other page");
}
return false;
});
});
Related
Currently im looping through links in a page and checking if the link contains a string to determine the url. Heres my current code:
$( ".domain a" ).each( function () {
if ($(this).is(':contains("imgur")')) {
This can detect if the element contains the string "imgur", but because of this is a link goes to a site like slimgur.com, it will also return true.
How can I properly check that the url is, in this example, imgur.com or any of its subdomains (i.imgur.com & m.imgur.com) and that a url such as slimgur.com wont return true?
Rather than check the text, use the properties associated to an <a> tag like hostname.
$( ".domain a" ).filter(function(){
return this.hostname === 'imgur.com';
}).doSomething();
DEMO
This will do it:
$( ".domain a" ).each( function() {
var str = 'imgur';
if($(this)[0].hostname.split('.').indexOf(str) > -1) {
console.log('Found ' + str);
}
})
You could do something like: JS Fiddle
$('a').each(function () {
var url = "yahoo.com";
var anchor = $(this).attr('href');
var domain = url_domain(anchor);
if (url === domain) {
//Do something here
}
});
function url_domain(data) {
var a = document.createElement('a');
a.href = data;
return a.hostname;
}
url_domain() function found here: Extract hostname name from string
I have this example in JsFiddle.
http://jsfiddle.net/PtNfD/114/
Yahoo
Not working
$(document).ready (function () {
$('#changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
The href change works in the first link, but not in the second. How can I make it work for both links??
The number of links in my page is dynamic, because I create the links with PHP, so I need the href change to work in all generated links.
id attributes must be unique. You should convert the value changeMe to a classname for use on multiple elements. Then your existing code should work:
Yahoo
Not working
$(document).ready (function () {
$('.changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
Optionally, you could add a unique id to the second anchor tag and modify the JavaScript code accordingly.
You cannot use an ID on two different elements in HTML. You need to asign each of those a different ID or the same class instead and then apply your href change on each of the IDs, or the class
IDs should be used once per webpage. Classes can be used more plentifully. Remember your specificity. Use class instead of id: http://jsfiddle.net/PtNfD/115/
Yahoo
Not working
$(document).ready (function () {
$('.changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
I'm using jquery and ajax to create a drawer (#DrawerContainer) and load content into it if I click a thumbnail in a gallery. My function is almost finished but I want to be able to close that drawer if I click again the opening button (now #current).
Here is a jsfiddle of my code: http://jsfiddle.net/RF6df/54/
The drawer element appears if you click a square/thumbnail, it's the blueish rectangle.
The current thumbnail is turned green.
I added a button in my drawer (not visible in the jsfiddle) to close it. I use this part of code for this purpose and it's working like a charm.
// Close the drawer
$(".CloseDrawer").click(function() {
$('#DrawerContainer').slideUp()
setTimeout(function(){ // then remove it...
$('#DrawerContainer').remove();
}, 300); // after 500ms.
return false;
});
Now I need my #current div to be able to close #DrawerContainer the same way .CloseDrawer does in the code above. Unfortunately adding a second trigger like this $("#current,.CloseDrawer").click(function() to my function isn't working... When clicking my "current" thumbnail, it just reopen the drawer instead of closing it...
How can I modify my code to close my #DrawerContainer with the "current" thumbnail?
Please keep in mind that I'm learning jquery, so if you can comment it could be of a great help. And please do not modify my markup or css, since everything works beside the closing part.
As per my understanding, you can use "toggle()" function which does exactly the same (i.e, toggle visiblity).
$('#DrawerContainer').toggle();
EDIT:
Updated the script to work.
$(document).ready(function() {
$.ajaxSetup({cache: false});
$('#portfolio-list>div:not(#DrawerContainer)').click(function() {
if ($(this).attr("id") != "current")
{
// modify hash for sharing purpose (remove the first part of the href)
var pathname = $(this).find('a')[0].href.split('/'),
l = pathname.length;
pathname = pathname[l-1] || pathname[l-2];
window.location.hash = "#!" + pathname;
$('#current').removeAttr('id');
$(this).attr('id', 'current');
// find first item in next row
var LastInRow = -1;
var top = $(this).offset().top;
if ($(this).next().length == 0 || $(this).next().offset().top != top) {
LastInRow = $(this);
}
else {
$(this).nextAll().each(function() {
if ($(this).offset().top != top) {
return false; // == break from .each()
}
LastInRow = $(this);
});
}
if (LastInRow === -1) {
LastInRow = $(this).parent().children().last();
}
// Ajout du drawer
var post_link = $(this).find('.mosaic-backdrop').attr("href");
$('#DrawerContainer').remove(); // remove existing, if any
$('<div/>').attr('id', 'DrawerContainer').css({display: 'none'}).data('citem', this).html("loading...").load(post_link + " #container > * ").insertAfter(LastInRow).slideDown(300);
return false; // stops the browser when content is loaded
}
else {
$('#DrawerContainer').slideUp(300);
$(this).removeAttr("id");
}
});
$(document).ajaxSuccess(function() {
Cufon('h1'); //refresh cufon
// Toggle/close the drawer
$("#current,.CloseDrawer").click(function() {
$('#DrawerContainer').slideToggle()
setTimeout(function(){ // then remove it...
$('#DrawerContainer').remove();
}, 300); // after 500ms.
return false;
});
});
//updated Ene's version
var hash = window.location.hash;
if ( hash.length > 0 ) {
hash = hash.replace('#!' , '' , hash );
$('a[href$="'+hash+'/"]').trigger('click');
}
});
Also, updated it here: Updated JS Fiddle
EDIT -2: Updated Link
Hope this Helps!!
Hi I have a page that navigates using anchors. On load the index page (A) needs to jump to anchor. Fine I can do this with on load function but coming back to the page A from page B I want to jump to a different anchor. I have this working:
<!-- go to Anchor -->
<script type="text/javascript">
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#top") > -1){
window.location.hash="top";
} else {
window.location.hash="middle";
}
}
</script>
#middle is the anchor to use when coming from a link that contains no anchor (or from typing the address into the url bar). I want to add three more 'if's'. I am fairly new at js so bear with me if I am doing something silly. I tried this:
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#right") > -1){
window.location.hash="right";
} else {
window.location.hash="middle";
}
if(urllocation.indexOf("#bottom") > -1){
window.location.hash="bottom";
} else {
window.location.hash="middle";
}
if(urllocation.indexOf("#left") > -1){
window.location.hash="left";
} else {
window.location.hash="middle";
}
But not joy, the js breaks and no longer goes to #middle on page load.
I tried a wild card approach:
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#.") > -1){
window.location.hash=".";
} else {
window.location.hash="middle";
}
}
Again, no joy.
Any help please.. thanks kindly
I am not quite sure I understand the effect you are trying to achieve (since window.location.hash should already contain the hash part of your url), but your code should probably rather be
function goToAnchor() {
var urllocation = location.href;
if (urllocation.indexOf("#right") > -1) {
window.location.hash = "right";
} else if (urllocation.indexOf("#bottom") > -1) {
window.location.hash = "bottom";
} else if(urllocation.indexOf("#left") > -1) {
window.location.hash = "left";
} else {
window.location.hash = "middle";
}
}
I am also guessing that your 'wild card' approach is meant to use regular expressions:
function goToAnchor() {
var urllocation = location.href;
var hashMatch = urllocation.match(/#(.*)/)
if (hashMatch){
window.location.hash = hashMatch[1];
} else {
window.location.hash = "middle";
}
}
Again, I don't quite see what effect this code should have, since window.location.hash will probably have the same value before and after the assignment.
If you just want to go back to the hash in the URL, have you tried something like this?
var hash = window.location.hash || "middle"; //Get current hash or default to "middle" if no hash is currently set
window.location.hash = +new Date() + ""; //Remove the hash and set it to some random value
window.location.hash = hash; //Set to the old hash
Hi i want to trig a function when user click in page links for example abc.com/hello.html#variable1 i want to catch #varible1 and execute a function.
If you want to grab the string after the hash:
$("a[href*='#']").click(function() {
var hash = this.href.replace(/.*#(.*)$/, '$1');
// do something
return false
});
Capture the hash and substring it out:
$("a[href*='#']").click(function(e){
var hash = $(this).attr('href').substring($(this).attr('href').indexOf("#"));
//hash = #var
function(hash);
});
To attach logic to all hash-links, you can do the following:
$("a[href^='#']").click(function(e){
// user clicked an inpage link
});
If you want to trigger a function for links with hashes that are dynamically inserted, use this:
$(document).click(function (event) {
var target = $(event.target);
if (target.filter("a[href*='#']").size() > 0) {
var hash = target.attr("hash");
// Do something with hash.
event.preventDefault();
}
});