I am wanting to use jQuery to add the current browser window dimensions to the end of the href of certain a tags.
The specific a tags all have their href begin with secondary_imgs.php but other than that, differ by containing data, i.e. secondary_imgs.php?Id=x&Title=y. I could easily set all these tags to have a specific class if that helps the problem.
I think the best approach to this would be to append the &width=x&height=y to the end of the href on document ready, and then set a second function to replace those values, whenever the page is resized.
Alas, I am at a loss as to how to complete this. I have the constituent parts (I think), but need help combining them in the proper way.
Here’s what I have thus far:
$(document).ready(function () {
var width = $(window).width();
var height = $(window).height();
$("a[href^='secondary_imgs.php']").attr('href', function() {
return this.append('&w=width&h=height')
});
});
I tried to specify just the a tags who’s href begins with secondary_imgs.php. I think that would be the best way of specifying it. But beyond that, I don’t know where I’m making a mistake.
For the second half of this, where the values are replaced when the window is resized, I thought using .resize() would be the best to trigger the function, however I don’t know how to set it up to replace the values, not add to them.
Any help would be much appreciated. Thank you.
In the loop
thisrefers to a DOM element, so you can’t use theappendmethod on it. Besides, the append method adds elements inside an element, it doesn’t concatenate strings.To put the values of the
widthandheightvariables in the string you have to concatentate them into a string. Putting the variable names inside a string won’t evaluate them.If you want to get the window size at the moment that the user clicks on the link instead of the size when the page loads, then you would rather catch the click event, create a new URL and apply it yourself instead:
Edit:
To be compatible with other scripts that take over the link action, you would make sure that you bind your event before loading/activating that script, and only change the URL and write it back, but first checking if there are properties that needs to be removed: