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');

Tested fully works

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!