1

I am currently using...

$(function () { 
    var title = document.title; 
    var count = $('.div').length; 
    $(this).attr("title", title + ' (' + count + ') ' + ' - Category Page');
});

...to add a number to the page's title. Using this method only allows me to have whatever comes after the 'count' + - to have the same wording.

How would I go about changing this so that in the HTML title tag, I can have - Category Page, or whatever inline, and to just have the number inserted by jquery before the hyphen?

HTML as is now ...

<title>Bicycles</title>

What I would like ...

<title>Bicycles - Category Page</title>

Then have jquery add the div count before the hyphen.

  • 2
    Can you give an example of your current output and your desired output? I'm not understanding the wording of your question fully. – Fillip Peyton Apr 09 '13 at 18:59
  • Did you mean $('div') or $('.div') ? Your current code counts any tags of class="div" which seems quite strange, and lower performance than it needs to be. – Chris Moschini Apr 09 '13 at 19:48

3 Answers3

1

In the end this is going to be up to you and there is no real standard to follow. It all depends on how you decide to scrub the content for your title. Such as deciding if it is coming from server side, if it is hard coded, etc. I say scrub your content for title, because in order to insert this number you are going to have to have some sort of a placeholder. Perhaps it makes sense to use () and then target that. Perhaps you would use _count_. That is where the implementation is up to you, and your code, to enforce. It must be this way because you are going to be searching inside of the string for that.

$(function () { //if you were inserting count into ()
 var title = document.title;
 var count = $('.div').length; 
 var ind = title.indexOf("()");
 title = title.substr(0,ind+1) + count + title.substr(ind+2,title.length);
 $(this).attr("title", title);
});

Another approach would be to track the two substrings noted above. Namely the prefix and suffix. This way you could do something much simpler.

$(function () {
 var prefix = "Some Title";
 var suffix = "Category";
 var count = $('.div').length; 
 $(this).attr("title", prefix + ' (' + count + ') ' + ' - ' + suffix);
});
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

Use sprintf (SO question with links and explanation explanation on it). Note it's not in the standard javascript library, but the extension.

Something like

<!--in the title-->
<title>There are %d rabbits in the basket</title>

$(function () { 
    var title = document.title; 
    var count = $('.div').length; 
    $(this).attr("title", sprintf(title, count));
});
Community
  • 1
  • 1
J0HN
  • 26,063
  • 5
  • 54
  • 85
0

Try

$(function () { 
    var title = document.title; 
    var count = $('.div').length;

    document.title = title + "( " + count + " ) - Category Page"; 
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157