views:

28

answers:

2

I'm making a tiny script that adds a class of "external" to all external links, then when someone click an external link, it shows a div.question-wrapper that has a div.follow and a div.dontfollow in it, it also displays the url of the link you clicked in the div.question-wrapper. the only problem i'm having is copying the href attr of the link clicked to the button div.follow.

jquery:

$(".external").click(function() {
    thisurl = $(this).attr('href')
    $("#question-wrapper").fadeIn('normal')
    $("#follow").attr('href', "($(this).attr('href'))")
        return false;   
    $("#dontfollow").click(function() {
        $("#question-wrapper").fadeOut('normal')
    })
    $("#question-wrapper span").html(
        $(this).attr('href'))
        return false;
    }) 

html:

<div id="question-wrapper">
    Would you like to continue on to 
    <span id="url">space where link is</span>?
    <div id="follow">CONTINUE</div>
    <div id="dontfollow">STAY HERE</div>
</div>
A: 

A DIV cannot have a HREF attribute.

bazmegakapa
+1  A: 

You have the right idea, but divs cannot have hrefs, so I would use two a tags in the #question-wrapper making your HTML look like:

<div id="question-wrapper">
    Would you like to continue on to 
    <span id="url">space where link is</span><br/>
    <a id="follow">CONTINUE</a><br/>
    <a id="dontfollow" href="#">STAY HERE</a>
</div>

Also, if you put the href in quotes then it'll display literally, so

$("#follow").attr('href', "($(this).attr('href'))");

Will make the #follow if it is an A look like:

<a href="($(this).attr('href'))">blah</a>

Also, you already created thisurl so use it. Also use var, since without declaring them variables become global (properties of window):

$("#follow").attr('href', thiurl);

So the entire thing would look like:

$(function() {                                            // <== DOC ready

    $("#question-wrapper").hide();                        // Hide the QR to begin

    $("a.external").click(function() {    // Click handler for all external links

        var thisurl = $(this).attr('href'),                            // The url
            $qr = $("#question-wrapper");                               // The QR

        $qr.fadeIn('normal');                                      // Show the QR

        $("#follow").attr('href', thisurl);              // Set the URL of FOLLOW

          // Make #url a working link too
        $("#url").html('<a href="' + thisurl + '">' + thisurl + '</a>');

        $("#dontfollow").click(function() {
            $qr.fadeOut('normal');
            return false;
        });

        return false;
    });
});​

Try it out with this jsFiddle

Peter Ajtai