vlada
vlada

Reputation: 33

Change Title's content on tab click

I have a little problem. I want to change my page title when I click on 1 of 5 tabs that I have on my page. The title of that page should change based on what tab was clicked. If would go something like this:

<div id="tab1"></div>
<div id="tab2"></div>
<div id="tab3"></div>
<div id="tab4"></div>
<div id="tab5"></div>

When clicked on tab1, title should change to "tab1, when clicked on tab2, title should change to tab2 and so on...

I tried with this jquery, but it didn't work. :)

<script type="text/javascript">
$(document).ready(function (){
    ('#tab2').click(function ()}{
        (document).title ('tab2');
    })
});

Can you please help me with that?

Thank you....

Upvotes: 1

Views: 2205

Answers (3)

Redhya
Redhya

Reputation: 683

Pure Js I can give you short version also

function changeTitle(pagetitle){
document.title = pagetitle;
}
document.getElementById('tab1').onclick = function(){changeTitle("tab1")};
document.getElementById('tab2').onclick = function(){changeTitle("tab2")};
document.getElementById('tab3').onclick = function(){changeTitle("tab3")};
document.getElementById('tab4').onclick = function(){changeTitle("tab4")};
document.getElementById('tab5').onclick = function(){changeTitle("tab5")};
<div id="tab1">A</div>
<div id="tab2">B</div>
<div id="tab3">C</div>
<div id="tab4">D</div>
<div id="tab5">E</div>

Upvotes: 1

SvenL
SvenL

Reputation: 1954

An elegant solution could also be if you would make use of the data() method in jQuery. Then you could simply define your preferred title for each tab that should be displayed in the title tag and it's not bounded anymore to the name of your id.

HTML

<div id="tab1" data-title="Tab 1"></div>
<div id="tab2" data-title="Tab 2"></div>
<div id="tab3" data-title="Tab 3"></div>
<div id="tab4" data-title="Tab 4"></div>
<div id="tab5" data-title="Tab 5"></div>

jQuery

$("div").click(function(){
  document.title = $(this).data("title");
});

Upvotes: 1

RysQ
RysQ

Reputation: 348

Try this

<div class="change-title" id="tab1">1</div>
<div class="change-title" id="tab2">2</div>
<div class="change-title" id="tab3">3</div>
<div class="change-title" id="tab4">4</div>
<div class="change-title" id="tab5">5</div>

<script>
$(document).ready(function() {
    $('.change-title').on('click',function(){
         document.title = $(this).attr('id');
    });
});
</script>

Upvotes: 3

Related Questions