I have a html element which is styled (using jquery) with a background image targeted thru its class name.
When I remove the class the background image stays - which is not what I expected or want.
test.html
<div id='log' class='tile'>HELLOWORLD</div>
test.css
.tile{
background: none;
}
test.js
$('.tile').css("background-image", "url(tile.jpg)"); // We see image
$('#log').toggleClass('tile'); // We still see image
After banging my head I think I know whats happening. The css is being applied to the element - NOT to the 'class'.
How can I target a specific css rule so that its key values can be updated?
If that makes sense.
If you wan to change the css rules of the ".tile" class, then you can do it.
There is a post that explains it very well :
function changeBackgroundImage(className, value){
var ss = document.styleSheets;
for (var i=0; i<ss.length; i++) {
var ss = document.styleSheets;
var rules = ss[i].cssRules || ss[i].rules;
for (var j=0; j<rules.length; j++) {
if (rules[j].selectorText === className) {
rules[j].style.backgroundImage = value;
}
}
}
}
You can call it like this :
changeBackgroundImage(".tile","url(tile.jpg)");
The problem is that you´re setting the background-image as an inline stlye that overrides any stylesheet rules. Toggling the class won´t have any affect.
You can either have set the background through a styleheet rule and then add a class that removes it;
#log {
background-image: url(tile.jpg);
}
#log.tile {
background: none;
}
or you could just use !important as;
.tile {
background: none !important;
}
...it might be the other way around but you get the point? :)
try removing class tile and applying new class with bg: none
in effect - when needed apply class with bg, when not needed - without
No need for jQuery in this case. You can use plain old JavaScript. Check out this tutorial:
javascriptkit.com - Changing external style sheets using the DOM
You can't change the class itself without re-writing that declaration in the stylesheet, you ARE working only with the element in the selector.
Try:
$('.tile').css("background-image","none")
$('#log').toggleClass('tile',true);
I would make the background image part of the class as a css style:
.tile {background-image: url('tile.jpg')};
and then remove the class when necessary with jquery
$('#log').removeClass('tile');
you could have two classes in your css...
.tile{
background: none;
}
.tile-w-image
{
background-image: url(tile.jpg);
}
and then with jquery just toggle the classes...
$("#log").toggleClass('tile').toggleClass('tile-w-image');
I'm sure this is just one of many ways of doing this. I hope it helps.
You are very close.
It seems like you are adding inline CSS to your element and then trying to toggle the class. You should keep CSS styling separate in most cases:
HTML:
<div id='log' class='tile'>HELLOWORLD</div>
jQuery (I imagine this should be done on click or another event):
$('#log').toggleClass('tile'); // We still see image
If the "tile" class is already written to the HTML, then toggle-ing it will remove it.
CSS:
.tile{
background-image: url(tile.jpg);
}
Related
I have this DOM
<div class="slotvideo">
<div class="posterimage"></div>
</div>
I can't modify this html code but I need to add an SVG icon. This SVG is used for a function. On click I need to reach the bottom of the page. I create this CSS
.posterimage::before {
content: "";
background-image: mysvg;
}
Now, I can't manipulate pseudo element but I can't find another solution for doing it. How could you fix this problem?
I couldn't find what do you actually want. but about manipulating pseudo-elements, it's not possible. But there is a work-around.
You can define another class name like .active change the element's class to it for controlling pseudo-element.
.posterimage {
/* anything... */
}
.posterimage.active::before {
content: "";
background-image: mysvg;
}
don't forget, psuedo-elements are inline by default, so if you want this background-image to show up, you need to make it display: block and define a set of width and height though.
and it's done. you can use that .active class to have controll of showing ::before or not by JavaScript.
Just a quick question... how is it that if I have the following CSS:
li { background:red; }
li:hover { background:blue; }
With the following JS (or something similar):
document.getElementsByTagName("li")[0].style.backgroundColor="yellow";
My list elements no longer turn blue when I hover over them? I've tested this both on Chrome and FF. And example can be seen here: http://jsfiddle.net/42bQr/. Any ideas?
This is because inline styes are more specific, you can override inline styles with the following:
li:hover { background:blue !important; }
It's because the style is "inline," which takes priority.
Check out this fiddle here to see what's happening: http://jsfiddle.net/9m3qw/
The output of the fiddle is:
<div class="red-bg" style="background-color: yellow;">hello</div>
The reason is because you are setting the style as an inline style which is the most specific. So when you click on a list item, the result is effectively:
<li style="background-color: yellow;">My List Element 1</li>
The following list of selectors is by increasing specificity:
Universal selectors
Type selectors
Class selectors
Attributes selectors
Pseudo-classes
ID selectors
Inline style
To get around this, you could instead assign a class to the list item with:
var listEls = document.getElementsByTagName("li");
for (var i = 0; i <= listEls.length - 1; i++) {
listEls[i].onclick = function () {
this.className = 'yellow'
};
}
where
.yellow {
background:yellow;
}
jsFiddle example
This is happening because you have applied inline style to your selector which has more specifity.
Try this Fiddle
li:hover { background:blue; !important}
If you prefer to use Javascript, then you can use Element ClassList API. But it is only supported in major browsers. Browser Compatibility Matrix. Check out this code
Javascript
var listEls = document.getElementsByTagName("li");
function addYellowClass() {
this.classList.add('bg-yellow');
}
for (var i = 0; i <= listEls.length - 1; i++) {
listEls[i].onclick = addYellowClass;
}
JSBIN Example
As the others have said the inline style takes priority when you click it. You may want to use a hover/mouseover event to add a class ie $(this).addClass('blueBG') with the background of blue that is removed onmouseout if that is the effect you are going for.
"background-color" is more specific than "background" thus it takes priority in your final style. essentially your JavaScript code is overwriting both of CSS properties because it has more weight.
try using background-color as a property in both the CSS and in the JavaScript.
I've got a text/html slideshow with Javascript however upon cycling of new text I also need the script to trigger the :hover class on the menu item corresponding to the content present in the slideshow.
For a visual example please see: http://i.stack.imgur.com/mkyMJ.png
I've uploaded the JS code to http://pastebin.com/Kp4a7VXP for viewing.
Would really appreciate your help on this guys! :)
Thanks so much!
Kind Regards,
Jake
It may not make sense to try to mimic the hover state, so it may be better to have a css class such as .active added to the element you want the hover state for, and then include the css from the hover state in that class.
I'm assuming you have a CSS like
.item{
/* normal appearance */
}
and
.item:hover{
/* appearance when mouse over */
}
but as far as I know, there's no way to trigger the pseudo class :hover via javascript. But you can use a standard class for this like (but for semantics I would name it like .currentSlide or .activeSlide)
.item:hover,
.item.hover{
/* appearance when mouse over
or selected */
}
and then you can add and remove that class using javascript for the current slide element, like:
currentSlideDiv.classList.add("hover");
EDIT:
You can use a function like this, and call highlightCurrentSlideName(currentContentItem); inside NextClick() and PreviousClick()
function highlightCurrentSlideName(slideIndex){
var slideNameList = jQuery('.contentmenu a');
jQuery(slideNameList).removeClass('current'); //unhighlight all slide names
var currentSlide = slideNameList[slideIndex]; //select a slide name by a numeric index
jQuery(currentSlide).addClass('current'); //highlight that element
}
and add a class on your CSS file, and style it whatever you want.
.contentmenu a.current{
color: lightblue;
background-color: gray;
}
PS: I'm not a jQuery programmer I always write pure javascript, just noticed you have it there already.
I've got a class with the display set to none I'd like to in Javascript now set it to inline I'm aware I can do this with an id with getElementById but what's the cleanest way to do it with a class?
You can do that — actually change style rules related to a class — using the styleSheets array (MDN link), but frankly you're probably better off (as changelog said) having a separate style that defines the display: none and then removing that style from elements when you want them no longer hidden.
Do you mean something like this?
var elements = document.getElementsByClassName('hidden-class');
for (var i in elements) {
if (elements.hasOwnProperty(i)) {
elements[i].className = 'show-class';
}
}
Then the CSS
.hidden-class { display: none; }
.show-class { display: inline; }
You can use getElementsByClassName in which you'll get an array of elements. However this is not implemented in older browsers. In those cases getElementsByClassName is undefined so the code has to iterate through elements and check which ones have the desired class name.
For this you should use a javascript framework such as jQuery, mootools, prototype, etc.
In jQuery it could be done with a one-liner as this:
$('.theClassName').css('display', 'inline')
you can create new style rule instead.
var cssStyle = document.createElement('style');
cssStyle.type = 'text/css';
var rules = document.createTextNode(".YOU_CLASS_NAME{display:hidden}");
cssStyle.appendChild(rules);
document.getElementsByTagName("head")[0].appendChild(cssStyle);
$("#YOUR_DOM_ID").addClass("YOUR_CLASS_NAME");
You may like to exploit/rewrite this function:
function getStyleRule(ruleClass, property, cssFile) {
for (var s = 0; s < document.styleSheets.length; s++) {
var sheet = document.styleSheets[s];
if (sheet.href.endsWith(cssFile)) {
var rules = sheet.cssRules ? sheet.cssRules : sheet.rules;
if (rules == null) return null;
for (var i = 0; i < rules.length; i++) {
if (rules[i].selectorText == ruleClass) {
return rules[i].style[property];
//or rules[i].style["border"]="2px solid red";
//or rules[i].style["boxShadow"]="4px 4px 4px -2px rgba(0,0,0,0.5)";
}
}
}
}
return null;
}
to scan all style sheets attached pass "" as third argument, otherwise something like "index.css"
ruleClass contains starting '.'
if (rules[i].selectorText && rules[i].selectorText.split(',').indexOf(property) !== -1) condition improvement found here https://stackoverflow.com/a/16966533/881375
don't forget to use javascript syntax over css properties, e.g. box-shadow vs. boxShadow
Although this is long gone, here a few remarks:
Using display: inline to make things visible again may spoil the
page flow. Some elements are displayed inline, others block etc. This
should be preserved. Hence, only define a .hidden style and remove it
to make things visible again.
How to hide: There are (at least) two ways to hide elements, one is
the above mentioned display: none which basically makes the element
behave as if it was not there, and the visibility: hidden which
renders the element invisible but keeps the space it occupies.
Depending on what you want to hide, the visibility may be a better
choice, as other elements will not move when showing/hiding an
element.
Adding/removing classes vs. manipulating CSS rules: The result is
quite different. If you manipulate the CSS rules, all elements having
a certain CSS class are affected - now and in the future, i.e. new
elements dynamically added to the DOM are also hidden, whereas when
you add/remove a class, you must make sure that newly added elements
also have the class added/removed. So, I'd say adding/removing
classes works well for static HTML, whereas manipulating CSS rules
might be a better choice for dynamically created DOM elements.
To change CLASS you need to edit document stylesheets
[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
.style.display='inline';
[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
.style.display='inline';
.box {
margin: 10px;
padding: 10px;
background: yellow;
display: none
}
<div class="box" >My box 1</div>
<div class="box" >My box 2</div>
<div class="box" >My box 3</div>
Best way to do it is to have a hidden class, like so:
.hidden { display: none; }
After that, there is a className attribute to every element in JavaScript. You can just manipulate that string to remove occurrences of the hidden class and add another one.
One piece of advice: Use jQuery. Makes it easier to deal with that kind of stuff, you can do it like:
$('#element_id').removeClass('hidden').addClass('something');
When you write real CSS you could do
.blue { color: blue; }
and if you added the class "blue" to an element after loading, it would turn blue.
In JavaScript you would have to do something like
var blue = document.getElementsByClassName('blue');
for (var i = 0; i < blue.length; i++)
blue[i].style.setProperty('color', 'blue');
The problem with the JavaScript version is if you did
document.getElementById('someId').className += " blue";
it would have the class blue, but it would not turn blue.
Is there any way (preferably simple) to add the style to the selector rather then directly to the elements with that selector?
The most common way is defining .blue { color:blue; } in the CSS beforehand, then adding the class to the element via JS. That way styles are in the CSS and only class names are in the JS, making it more flexible instead of hardcoding dozens of css keys/values in the JS.
See this question. You can add a <style> element via JavaScript.
The HTML
<div id="test">This will turn blue</div>
<button onclick="addClass()" >add Class </button>
The Javascript
function addClass(){
document.getElementById('test').className += 'blue';
}
The CSS
.blue{
color:blue;
}
This works in FF IE7 and Chrome. Perhaps there is something else going on in your code which is stopping this from working.