0

I need to check the number of characters in class span, then change CSS according to the number.

For example, if length of title is less than 29, the title color should be yellow. If length of title is greater than 29, the title color is blue.

I add the condition if(x > 29), but it cannot work, how can I correct my script ?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script>
 $(document).ready(function(){

$(".block .title h2 span").each(function(index) {
   var x=$(this).text().length;

      if(x > 29){
        $(".block .title h2 span").css("color","blue");
        $(".block .title h2").css("padding-top","0px");
                }
      else{
        $(".block .title h2 span").css("color","yellow");
        $(".block .title h2").css("padding-top","18px");
        };

});

});

closed as off-topic by Eric Alexander Jul 23 '15 at 15:34

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Programming questions not specific to SharePoint are off-topic here, but can be asked on Stack Overflow." – Eric Alexander
If this question can be reworded to fit the rules in the help center, please edit the question.

  • Why do you think that it does not work? – Dylan Cristy Jul 23 '15 at 15:24
  • @DylanCristy if length of title is less than 29, the title color should be yellow, but all titles with the color blue right now, in fact some titles' length is less than 29 – AnnaCICI Jul 23 '15 at 15:27
  • 1
    This is a basic javascript question, and should be on SO. – wjervis Jul 23 '15 at 15:29
  • Agreed. But I answered it anyway. :) – Dylan Cristy Jul 23 '15 at 15:35
  • I was typing up the same thing. Code is working perfectly fine, just flawed in logic. – wjervis Jul 23 '15 at 15:36
2

Ok, here's what's happening:

// select ALL elements that are .block .title h2 span and loop through them
$(".block .title h2 span").each(function(index) {

   // find the length of the text of THIS PARTICULAR element     
   var x=$(this).text().length;

   // if the length of THIS PARTICULAR element is > 29
      if(x > 29) {

        // change the CSS of ALL elements that match .block .title h2 span      
        $(".block .title h2 span").css("color","blue");
        $(".block .title h2").css("padding-top","0px");
      }
      else {

        // change the CSS of ALL elements that match .block .title h2 span 
        $(".block .title h2 span").css("color","yellow");
        $(".block .title h2").css("padding-top","18px");
      };
});

You really want your if statement to look like this:

if (x > 29) {
    $(this).css("color","blue");
    $(this).closest("h2").css("padding-top","0px");
} else {
    $(this).css("color","yellow");
    $(this).closest("h2").css("padding-top","18px");        
}

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