xinthose
xinthose

Reputation: 3828

jQuery href navigation

I am trying to make a simple page. I only want to show one division at a time and navigate in the body using href #'s. I think I need to show / hide based on an anchor link being clicked. Thank you.

HTML

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="javascript.js"></script>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
    <meta charset="utf-8">
</head>
<body>

    <div id="home">
        <a href="#" rel="test">Go To Testing Number</a>
    </div>

    <div id="test">
        <a href="#" rel="home">Home</a>
        <p>Testing Number</p>
        <input type="number" value="0" />
    </div>


</body>
</html>

JavaScript

$(document).ready(function(){
    $('div').not('#home').hide();   // show home page first
});

// this function needs to change I think, it does not work properly
$('a').on('click', function(){
   var target = $(this).attr('rel');
   $(target).hide();
   $("#"+target).show();
});

Upvotes: 0

Views: 578

Answers (3)

xinthose
xinthose

Reputation: 3828

I figured it out after hours of research online. Simple and powerful.

$(document).ready(function(){
    $('div').not('#home').hide();   // show home first

    $('a').click(function() {
        var target = $(this).attr('href');
        $('div').not(target).hide();
        $('div').filter(target).show();
    });
});

JSFiddle Solution

Upvotes: 1

Phil
Phil

Reputation: 607

//this should work fine 
$('a').on('click', function(){
    var     target = $(this).attr('rel');
    If(target == "home"){
        $("#home" ).hide();
        $("#test").show();
    }else{
        $("#test" ).hide();
        $("#home").show();
    }
});

Upvotes: 3

Barmar
Barmar

Reputation: 780994

You're showing the selected DIV correctly, but your code for hiding the other DIVs is wrong. Why did you think $(target) would select the DIV that's already showing?

Give all the DIVs for different tabs the same class so you can hide them all in one call.

<div id="test" class="tab">
    <a href="#" rel="home">Home</a>
    <p>Testing Number</p>
    <input type="number" value="0" />
</div>

Then the jQuery would be:

$("a").click(function() {
    var target = $(this).attr("rel");
    $(".tab").hide();
    $("#" + target).show();
});

Upvotes: 1

Related Questions