March 12, 2012
Compare attributes title to url params
Question by swan
I have a small plugin from the net to fetch url params:
$.extend({
getUrlVars: function () {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function (name) {
return $.getUrlVars()[name];
}
});
This extracts params from url, e.g.:
http://mysite.com/page?slideshow=video&title=General Overview
I want to match the title param to an existing link which has the same title as the param “title”, and do something if match found, in this case General Overview:
<a href="/some-colorbox-page" class="colorbox" title="General Overview">View video</a>
var isSlideshow = $.getUrlVar('slideshow');
if (isSlideshow === 'video' && $('a.colorbox', '.video').length) {
var titleAttr = $('a.colorbox').attr('title');
var title = $.getUrlVar('title');
$(window).bind('load', function () {
if (titleAttr === title) {
$('a.colorbox', '.video').each(function()) {
$(this).trigger('click');
});
}
});
}
But this doesn’t work.
Shortly, when a visitor visit the link (http://mysite.com/page?slideshow=video&title=General Overview)
, I want to trigger an event click to an element that has the same title as the value of url param “title”.
Note the white space between General and Overview. This thing makes the query a bit complicated. I can not control the title attributes, but may control the title param.
Any help would be very much appreciated.
Thanks
Answer by Starx
Try this
title = decodeURIComponent(
(RegExp('title=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
$('a[title='+title).trigger('click');