13th
JUN

Get HREF attribute keeps on returning absolute link not relative link

Posted by Lee under Programming, jQuery

Whilst working on our new Image Manager in Breeze we came across an interesting bug that was causing images to be incorrectly linked to in the editor due to Internet Explorer (IE6 & IE7 intermittently) returning the wrong HREF value for a link.

The link we were getting the HREF value from was set as below

<a href="uploads/images/photo.jpg"></a>

We were trying to obtain the HREF using jQuery with the following code:

$(this).attr('href')

But this would return the absolute link (eg. http://www.domain.com/uploads/images/photo.jpg) instead of the HREF that was set. Usually we would use absolute links everywhere but didn’t in this case as we just needed the image address.

We then tried the basic javascript way of getting the href as below which still didn’t work:

<a href="uploads/images/photo.jpg" onclick="alert(this.href);return false;"></a>

We then found the following post which worked but as our system was using AJAX later to get more links for some reason IE still wanted to automatically append the full URL.

<a href="uploads/images/photo.jpg" onclick="alert(this.getAttribute('href',2));return false;">

In the end we went for the way that was our last option. We output the absolute link and we set a hidden input field with our base_url (eg. http://www.domain.com/) and then did a replace over the href with the base_url. Not the most elegant solution but unfortunately the only way we could get it to work:

var href = $(this).attr('href');
var imgPathFull = href.replace($('input[@name=base_url]').val(),'');
var img = '‘;

Leave a Reply

(required)
(will not be published) (required)

The Lab is the web development blog for PX Webdesign that covers many subjects from PHP, CSS, jQuery, CodeIgniter, Design and XHTML / HTML