Question

For any links with a particular CSS class, I'd like to control whether the links open in the same window, a new window or a pop-up (using onclick), based on the user's selection from a group of radio buttons -- and then save that choice in a cookie (all using jQuery). Anyone know how to accomplish this?

Was it helpful?

Solution

This is probably how I'd do it... (you will need the jQuery cookie plugin):

<script language="javascript">
$(function() {
    if($.cookie('link_pref')) {
    var link_pref = $.cookie('link_pref');
        $('#link_options_form :radio[value="'+ link_pref+'"]')
        .attr('checked','checked');
    }
    $.cookie('link_pref',$('#link_options_form :radio:checked').val(), {expires: 0});
    $('#link_options_form :radio').unbind('click').bind('click',function() {
         $.cookie('link_pref', $(this).val(), {expires: 0});
    });
    $('a').unbind('click').bind('click',function() {
        var link_pref = $.cookie('link_pref');
        var href = $(this).attr('href');
        var link_txt = $(this).text();
        switch(link_pref) {
            case 'new':
                $(this).attr('target','_blank');
                return true;
            case 'pop':
                window.open(href,link_txt,'width=640,height=480,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
                return false;
            case 'greybox':
                // Other options found here: 
                // http://orangoo.com/labs/greybox/advance_usage.html
                GB_show(link_txt, href);
                return false;
            default:
                $(this).attr('target','_self');
                return true;
        }
    });
});
</script>

<form id="link_options_form">
    <label><input type="radio" name="link_options" value="same" /> Open in Same Window</label>
    <label><input type="radio" name="link_options" value="new" /> Open in New Window</label>
    <label><input type="radio" name="link_options" value="pop" /> Open in Pop-Up Window</label>
    <label><input type="radio" name="link_options" value="greybox" /> Open in Greybox</label>
</form>

Edit: Sorry that I didn't test it first. I had a few typos in there and I forgot to set the cookie to begin with (sorry). I've tested it and it now works with your HTML. Use the newly edited code above. ;-)

Edit 2: I added a direct link to the cookie plugin just in case you, for some reason, aren't using the right one.

Edit 3: Personally, I wouldn't set the radio button as checked in javascript... you can access the same cookie in your server-side language I believe. But, I've provided a way that should work in my newly edited code.

Edit 4: The initial setting of the checked radio buttons bug has been fixed. It should really really work this time. For real. o_0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top