Dan
Dan

Reputation: 13

Why is this simple jQuery not working?

I am trying to send the user to either google or yahoo depending on which link they clicked, if they clicked the 1st one they will be taken to google, and if they clicked the seond they will be taken to yahoo.

So for the window.location function I am using a variable called website which I'm defining based on which link the user clicked. But it's not working. The variable isn't being recognized:

<script type="text/javascript">
    $(document).ready(function(){

        // define the variable website based on which link is clicked
        $('a').eq(0).click(function() {
            var website = 'http://google.com';
        });
        $('a').eq(1).click(function() {
            var website = 'http://yahoo.com';
        });

        $('a').click(function() {
            window.location = website;
        });

    });
</script>

<a href="#">Link 1</a>
<br />
<a href="#">Link 2</a>

Upvotes: 0

Views: 332

Answers (3)

Ricardo
Ricardo

Reputation: 737

<a id="link1" href="http://google.com">Link 1</a> 
<br /> 
<a id="link2" href="http://yahoo.com">Link 2</a>

Upvotes: 0

Alpesh
Alpesh

Reputation: 5405

More better way of doing it -

<script type="text/javascript">
  $(document).ready(function(){
   var website = '';
   $('a').click(function() {
    var clicked = $(this).index('a');
    switch(clicked){
    case 0:
    website = "http://google.com";
    break; 

    case 1:
    website = "http://rediff.com";
    break;        
    }
     document.location= website;

     });
   });
</script>

<a href="#">Link 1</a>
<br />
<a href="#">Link 2</a>

Upvotes: 1

Tim M.
Tim M.

Reputation: 54417

<script type="text/javascript">

    var _website = null;

    $(document).ready(function ()
    {
        $('a').eq(0).click(function ()
        {
            _website = 'http://google.com';
            Navigate();
        });

        $('a').eq(1).click(function ()
        {
            _website = 'http://yahoo.com';
            Navigate();
        });
    });

    function Navigate()
    {
        document.location = _website;
    }

</script>

<a id="link1" href="#">Link 1</a>
<br />
<a id="link2" href="#">Link 2</a>

Upvotes: 0

Related Questions