Abap newbie
Abap newbie

Reputation: 173

jquery .css() rule isnt getting applied

I have this code,everything works fine but .css('color','red') rule is not getting applied.I tried different ways but could'nt find any.

$('#menu li').each(function() {
$(this).hover(function() {
$(this).text().charAt(0).css('color','red');
});
});

But this code works fine.Cant figure what is wrong with above code.

$('#menu li').each(function() {
$(this).hover(function() {
$(this).css('color','red');
});
});

Thank you for your responses.

Upvotes: 2

Views: 310

Answers (4)

jfriend00
jfriend00

Reputation: 707326

$(this).text().charAt(0) is a javascript string. It has no method .css().

So, you can't apply CSS to a single character in a javascript string.

If you want to apply a color to one character in the page, you'll have to get the text, add a span tag around the first character, add style to that, then set that HTML back on the DOM element.

I'd suggest changing your code to this:

$('#menu li').hover(function() {
    var text = $(this).text();
    text = "<span style='color: red'>" + text.charAt(0) + "</span>" + text.slice(1);
    $(this).html(text);
  }, 
  function() {
    $(this).html($(this).text());
});

You can see that one in action here: http://jsfiddle.net/jfriend00/9xCak/

I would not recommend using this jQuery because there are much better ways to do this. It can be done with pure CSS or you could just add/remove a class with your jQuery.

Note, that you don't need the each loop as you can just set a hover handler on the first jQuery selector and it will do .hover for all matched elements in the selector. Also, you have a second function in the hover call to set it back when the mouse leaves..

If you intend for the red to go away when the mouse leaves the li, then you could do this entirely with CSS. No jQuery is required.

HTML:

<li><span class="firstLetter">F</span>irst Menu Item</li>

CSS:

li .firstLetter:hover {color:red;}

Upvotes: 1

Arsen K.
Arsen K.

Reputation: 5660

If you have only one word, then jfriend00 answer is perfect. But if you want to apply style to every word in a string, I'd recommend you to read this Changing the value of the first letter of each word

Upvotes: 1

Seth Carnegie
Seth Carnegie

Reputation: 75130

charAt just returns a string, not a DOM object, therefore you can't use css with it. One option is to use CSS3's first-letter selector in plain CSS:

#menu li:hover:first-letter {
    color: red;
}

Another solution (though more clunky, slower, and less flexible) is to wrap the first character of every #menu li in a span tag and style that, but I recommend against it.

Upvotes: 3

Shawn Mclean
Shawn Mclean

Reputation: 57469

The first code wont work. You are trying to apply css to a character. Css can only be applied to html elements, which will affect your characters inside it.

Upvotes: 1

Related Questions