2

Is it possible with jquery to add new style declarations?

For example, pass:

{ "body": { "font-size": "12px" }, "table": { "xyz": "123" } }

etc etc

to a function I don't know without having to select those elements and do it like this:

$('body').css({"font-size": "12px"});
$('table').css({"xyz": "123"});

And second part of the question, is it possible to set css for the :hover pseudo class with jquery or do I need to use the .hover() function? If possible I just want css applied and not have to deal with on mouse in / out functions.

$('#element').find('a.thumbnail:hover').css({'background-color': '#efefef' });

does not work.

Thanks, Wesley

Variant
  • 17,279
  • 4
  • 40
  • 65

5 Answers5

5

You can alter the stylesheet itself with pure javascript through the document.stylesheets collection. see more here: http://www.howtocreate.co.uk/tutorials/javascript/domstylesheets

You can also use the jQuery plugin jRule to accomplish the same results: http://flesler.blogspot.com/2007/11/jqueryrule.html

Variant
  • 17,279
  • 4
  • 40
  • 65
4

Answer to part 1:

You would have to define a function to do that - try something like this:

function styleit(json)
{
    //loop through the json
    $.each(item, function(i, style){
      //apply styles
      $(i).css(styles);
    }
}

Answer to part 2:

I would put the css declaration in a class like:

.active a.thumbnail:hover { background-color: #efefef; }

Then use javascript to toggle the class in a parent element's context

$('#element').addClass('active');
willoller
  • 7,106
  • 1
  • 35
  • 63
0

For the first part, you are correctly adding styles to the body and table tags.

For the second part, this solution, while using .hover() seems to be a easier solution:

$('#element').hover(function() {
    $(this).css({'background-color': '#efefef' });
});
Phil
  • 10,948
  • 17
  • 69
  • 101
0

Try this :

$('a.thumbnail').hover(
    function(){
        $(this).css({'background-color':'#efefef'});
    },
    function(){
        $(this).css({'background-color':'normal-color'});
    }
);

Example : http://jsfiddle.net/jfhpg/1/

Hope it helps.

Sparkup
  • 3,686
  • 2
  • 36
  • 50
-1

You have to do it by selecting the dom element only. Also in order to set the hover styles you have to either set the styles using css or add/remove class names.

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • @Phil - He is asking whether it is possible to do it the way he wants. I answered it is not possible he has to do the way he is doing. I think I shouldn't get down vote for this. I didnt answer anything wrong here. – ShankarSangoli Jul 27 '11 at 18:42
  • You didn't answer it wrong, but it's a complete waste of an answer. I'll remove the down vote if you edit it... – Phil Jul 27 '11 at 19:41