-1
<div class="myclass selected">
    <h2 class = "title">#Content 1</h2>
</div>
<div class="myclass">
    <h2 class = "title">#Content 2</h2>
</div>
<div class="myclass">
    <h2 class = "title">#Content 3</h2>
</div>
<div class="myclass">
    <h2 class = "title">#Content 4</h2>
</div>

I want to show as "http://example.com/#content-1" in url and want to update for each selection. Is this possible to do that using jquery ?

7
  • do you want to click at #Content 1 and change url? Aug 24, 2012 at 1:17
  • 1
    Your question is unclear, please provide more information.
    – Ram
    Aug 24, 2012 at 1:18
  • I have no idea what you want.
    – j08691
    Aug 24, 2012 at 1:19
  • i want to change the url when i click using the next click funtion. Aug 24, 2012 at 1:20
  • I believe that you want anchors instead of h2 Aug 24, 2012 at 1:21

2 Answers 2

2
$('.myclass h2').click(function(){
    window.location = 'http://example.com/' + $.text(this).toLowerCase().replace(/ /g, '-');
});

Is there any reason you're not using regular links? Try this:

<div class="myclass selected">
    <h2 class="title">
        <a href="#content-1">#Content 1</a>
    </h2>
</div>
<!-- Add the others here... -->

Then, just add this script:

jQuery(function() {
    var hash = window.location.hash;
    hash && $('.myclass').removeClass('selected').filter(function(){
        return $(this).find('a').prop('href') == hash;
    }).addClass('selected');
});
7
  • We can also use window.location.hash.
    – Ram
    Aug 24, 2012 at 1:24
  • @undefined - The OP has not specified that they're currently on http://example.com/. Aug 24, 2012 at 1:25
  • In this code, when i refresh the page it starts from initial. Is this possible to get the same content which is on the url even i refresh the page ? Aug 24, 2012 at 1:32
  • @user1621335 - I'm truly sorry, but I do not understand your question. Aug 24, 2012 at 1:34
  • if this is my link "example.com/#content-3". when i refresh my page, it doesn't show the content 3. instead of that it show the content 1. Sorry for my bad english. Aug 24, 2012 at 1:35
0

Change this

 var selected = $('.selected');
    selected.removeClass('selected');
    selected.hide();

    var next = selected.next(".myclass");

to

 var selected = $('.selected');
 var next = selected.next(".myclass");
 selected.removeClass('selected');
 selected.hide();

You are removing the class selected before assigning it to next..

http://jsfiddle.net/wirey00/Jqfsn/1/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.