How to read href attribute with JQuery - javascript

I use $(this).attr('href') in JQuery to read the string in href="" attribute.
I have those kind of links:
Firefox and Chrome return me the code correctly. IE return me: http://127.0.0.1/1
How can i do?

You don't need to use the attr function when you're accessing a native property. You could use the anchor element's properties directly to get the pathname (i.e. the HREF without the domain or query string)
Basically: this.pathname
There's a bit of an inconsistency between browsers (some will show a leading forward slash in pathname and others won't). To get around this, just get rid of any potential leading slashes:
this.pathname.replace(/^\//,'')
A working example: http://jsfiddle.net/jonathon/3ET6p/
Even if you choose the other answers, I recommend you use the native .href on the object.
Just as an extra note to this. I fired up a VM of IE6 and all is well :)

Try via DOM element:
$(this)[0].href; or $(this)[0].getAttribute("href");
If the result is still the same, I suggest you using something not starting with the number.
.

I'd suggest checking which browser is being used. If it's IE, check if the current domain is "127.0.0.1". If it's not, do what #Saul suggested.

Related

Loop though DOM with jQuery to get some data- attribute value

This seems like a simple thing, but I keep getting "undefined"
I am trying out the "data-" HTML5 attribute and I am looping through a bunch of div tags that look like this:
<div id="myEvent"
data-scheduledOn="1399985100000"
data-eventStatus="3">
And I am looping through a bunch of these like this:
$('[id="myEvent"]').each(function(index, divItem) {
alert($(divItem).data("scheduledOn"));
}
But I keep getting "undefined" If I do this (get the attribute) it works fine:
alert($(divItem).attr("data-scheduledOn"));
So What am I missing?
http://api.jquery.com/data/
"The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks."
At least at this point in time, to use the .data function you have to attach the data using the function before you can read it back using the .data function.
If you need to read pre-existing data use the .attr or .prop functions.
It seems as though It is a naming problem as Hamza Kubba suggested, but just a bit different...
if I changed the name of the data attribute to "data-scheduled-on" I can retrieve it by .data("scheduledOn") OR using data-scheduledon and .data("scheduledon") also works.
So don't use CAPS for data- names is the moral of this story!
Please note that per HTML 5 specs, the attribute name should not contain any uppercase letters and some browsers such as FF & Chrome will change any uppercase letter to lowercase. That's why the following demo works if you access the data attributes with lowercase names:
http://jsfiddle.net/fiddleyetu/5LdQd/
$('div.myEvent').each(function(index, divItem) {
console.log($(divItem).data("scheduledon"));
console.log( $(divItem).data("eventstatus") );
});
Ans since you cannot have more than one element on a page with the same ID, I have used a class selector for the demo.
MORAL: Do not use UPPERcase; your browsers may not always be that 'understanding'.

How to get anything following the domain in a url, using Javascript

What is the best way to get the "anything" part after the domain part, using Javascript:
http://www.domain.com/anything
http://www.domain.com/#anything
http://www.domain.com/any/thing
For http://www.domain.com/#anything I would have to use window.location.hash. But for http://www.domain.com/anything I would have to use window.location.pathname.
I'm using:
window.location.href.replace(window.location.origin, "").slice(1)
Are there any caveats with this solution? Is there a better way?
Caveats:
location.origin is not supported by IE.
Other improvements: .slice is actually calling Array.prototype.slice. A method call that requires a prototype lookup is bound to be slower than accessing the element you need directly, escpeciallly in your case, where the slice method is returning an array with just 1 element anyway. So:
You could use location.pathname, but be weary: the standard reads:
pathname
This attribute represents the path component of the Location's URI which consists of everything after the host and port up to and excluding the first question mark (?) or hash mark (#).
but I think the easiest, most X-browser way of getting what you want is actually simply doing this:
var queryString = location.href.split(location.host)[1];
//optionally removing the leading `/`
var queryString = location.href.split(location.host)[1].replace(/^\//,'');
It's very similar to what you have now, except for the fact that I'm not using location.origin, which, as shown on MDN is not supported by MS's IE...
Another benefit is that I'm not calling Array.prototype.slice, which returns an array, and requires a prototype-lookup, which is marginally slower, too...
window.location.pathname + window.location.search + window.location.hash
I think this one is a little bit better. You dont have to use any functions here...

IE Object doesn't support this property or method

This is probably the beginning of many questions to come.
I have finished building my site and I was using Firefox to view and test the site. I am now IE fixing and am stuck at the first JavaScript error which only IE seems to be throwing a hissy about.
I run the IE 8 JavaScript debugger and get this:
Object doesn't support this property or method app.js, line 1 character 1
Source of app.js (first 5 lines):
var menu = {};
menu.current = "";
menu.first = true;
menu.titleBase = "";
menu.init = function(){...
I have tested the site in a Webkit browser and it works fine in that.
What can I do to fix this? The site is pretty jQuery intensive so i have given up any hope for getting it to work in IE6 but I would appreciate it working in all the others.
UPDATE: I have upload the latest version of my site to http://www.frankychanyau.com
In IE8, your code is causing jQuery to fail on this line
$("title").text(title);
in the menu.updateTitle() function. Doing a bit of research (i.e. searching with Google), it seems that you might have to use document.title with IE.
Your issue is (probably) here:
menu.updateTitle = function(hash){
var title = menu.titleBase + ": " + $(hash).data("title");
$("title").text(title); // IE fails on setting title property
};
I can't be bothered to track down why jQuery's text() method fails here, but it does. In any case, it's much simpler to not use it. There is a title property of the document object that is the content of the document's title element. It isn't marked readonly, so to set its value you can simply assign a new one:
document.title = title;
and IE is happy with that.
It is a good idea to directly access DOM properties wherever possible and not use jQuery's equivalent methods. Property access is less troublesome and (very much) faster, usually with less code.
Well, your line 1 certainly looks straight forward enough. Assuming the error line and number is not erroneous, it makes me think there is a hidden character in the first spot of your js file that is throwing IE for a fit. Try opening the file in another text editor that may support display of normally hidden characters. Sometimes copying/pasting the source into a super-basic text-editor, like Notepad, can sometimes strip out non-displayable characters and then save it back into place directly from Notepad.

REGEX / replace only works once

I'm using REGEX and js replace to dynamically populate a variable in a href. The following code works the first time it is used on the page, but if a different variable is passed to the function, it does not replace ANYTHING.
function change(fone){
$("a[href^='/application']").each(function(){
this.href = this.href.replace(/device=.*/,"device="+ fone);
});
}
The problem is that this.href actually returns a full absolute URL. So even your HTML is <a href="/foo"> the .href property will return http://mydomain.com/foo.
So your href attributes is being populated with a full absolute URL, and then the a[href^='/application'] selector doesn't match anymore, because the href attribute starts with the domain name, instead of /application.
.href returns a fully qualified URL, e.g. `http://www.mydomain.com/application/...'. So the selector doesn't work the 2nd time around since your domain relative URL has been replaced with a full URL, and it's looking for things that start with "/application".
Use $(this).attr('href').replace... instead.
Fiddle here: http://jsfiddle.net/pcm5K/3/
As Squeegy says, you're changing the href the first time around so it no longer begins with /application - the second time around it begins with http://.
You can use the jQuery Attribute Contains Selector to get the links, and it's probably also better practice to use a capture group to do the replacement. Like so:
$("a[href*='/application']").each(function(){
this.href = this.href.replace(/(device=)\w*/, "$1" + fone);
});
You'll need to add the g flag to match all instances of the pattern, so your regular expression will look like this:
/device=.*/g
and your code will look like:
this.href = this.href.replace(/device=.*/g,"device="+ fone);
The reason is that unless all you links start as "/device=." the regex wont work.
you need to use /.*device=.*/
the lack of global flag is not the problem. its the backslash in your pattern.

Why can't I use relative URLs with IE7?

I've been Googling for a while and can't seem to find an answer to this question. My problem is as follows:
For my jquery, I need my links to be relative rather than absolute. My PHP is set to return relative urls and everything is working fine, until I test it in IE7. For some reason, IE7 keeps changing my relative urls to abosulute, which breaks my js script. Is this normal? Is there a way to get around it?
For example:
IE8, Chrome, Firefox, Safari etc -
<a href='/page' onclick='click_handler(this);return false;'>clicky</a>
IE7 -
<a href='http://www.myurl.com/page' onclick='click_handler(this);return false;'>clicky</a>
What I do is grab the baseUrl at init, like:
var baseUrl = window.location.href.substring(0, window.location.href.lastIndexOf("/") + 1);
... and then in my URL handler, strip the baseUrl:
var url = $(this).attr("href").replace(baseUrl, "");
Also you can check if the href is "normalized" using .support():
$.support.hrefNormalized
(returns true if the browser makes no modifications when grabbing an href value, so it's currently false in IE.)
If I were you, I'd use browser detection and add a clause to strip the URL down to the relative path. I'm not 100% familiar with jQuery, but I imagine you could do it with a simple split and reconstruction, or REGEX query.
See jQuery URL Parser Plugin: http://plugins.jquery.com/project/url_parser
Looks like it has something to do with security issues - http://blogs.msdn.com/ie/archive/2005/08/15/452006.aspx
Right, it seems the best way to do this is to strip the domain out in jQuery. For anyone that has a similar problem, here is what my click event handler looks like:
var href_attr = element.getAttribute('href');
if (href_attr.indexOf('http://')>-1) {
href_attr = href_attr.substr(location.href.length-1);
};
Here's a modified version of JKS's answer that uses split instead of substring. A little more elegant IMO:
stripBaseUrl : function(url){
var urlArray = url.split("/");
return urlArray[urlArray.length - 1];
}

Categories

Resources