views:

48

answers:

5

I've got some p tags with the class PointsToggle

<p class="PointsToggle">POINTS STATEMENT - AVAILABLE 7AM TOMORROW</p>
<p class="PointsToggle">SOME OTHER TEXT</p>

And some jQuery like this

$('.PointsToggle').each(function() {
if ($(this).text = 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
    $(this).css('width', '510px');
}
else {
    $(this).css('width', '20px');
}
})​

But I can't seem to get it to work

Any ideas?

Thanks

Jamie

+6  A: 
$('.PointsToggle').each(function() {
  var $this = $(this);
  if ($this.text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
    $this.width(510);
  } else {
    $this.width(20);
  }
})​
Shay Erlichmen
Catch `$(this)` into a local variable at the start of function.
Andreas Grech
@Andreas You mean cache, done.
Shay Erlichmen
well, I meant catch...catch into a variable to cache the value.
Andreas Grech
+2  A: 

.text() is a function, so you're missing some parenthesis when calling it, like this:

if ($(this).text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {

Or a bit simpler overall in jQuery 1.4+:

$('.PointsToggle').width(function() {
 return $(this).text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW' ? 510 : 20;
})​;
Nick Craver
+3  A: 

You are using = which means assign. Try == instead.

Buh Buh
A: 
$(document).ready() {
    $('.PointsToggle').each(function() {
        if($(this).html() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
            $(this).width(510);
        } else {
            $(this).width(20);
        }
    })​
});

EDIT:

If it's possible I would have the code generating the html add another class. Then this can all be done with css. For example:

<p class="PointsToggle Toggled">POINTS STATEMENT - AVAILABLE 7AM TOMORROW</p>

<style>
    .PointsToggle {width:20px;}
    .PointsToggle.Toggled {width:510px;}
</style>
Arnar Yngvason
A: 

This will work:

$('.PointsToggle').each(function() {
if ($(this).text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
    $(this).css('width', '510px');
}
else {
    $(this).css('width', '20px');
}
})​
Roman