CSS get parent elements attribute - javascript

So i just ran into this problem. Let's say I have the following markup:
<article data-color='#123456'>
<header>...</header>
<a href='#'>Lorem ipsum</a>...
...
</article>
So I have an element with a custom color attribute. I want to have the header have it as a background color, and the link as a color (the color is either randomly generated or user-defined). Is there a way to do this is CSS alone? (I am aware that jQuery would do this without a problem, but I'd like to kepp things as pretty as possible, not using Javascript for styling alone.)

You can use an attribute selector in your CSS:
article[data-color="#123456"] header {
background-color: "#123456";
}
article[data-color="#123456"] a {
color: "#123456";
}
However, this assumes you can enumerate the data-color attributes in your CSS. If it's generated dynamically and can take any value, you can't do it in CSS -- it doesn't have variables or back-references.

Unfortunately CSS cannot do this. the JS is relatively simple though:
$('article').filter(function() {
return $(this).data('color');
}).each(function() {
var $el = $(this), color = $el.data('color');
$el
.find('header').css('background-color', color).end()
.find('a').css('color', color);
});
Example fiddle

I think you can do it like this:
article[data-color="#123456"] header {
background-color: attr(data-color color);
}
article[data-color="#123456"] a {
color: attr(data-color color);
}
UPDATE
The first answer is incorrect, it doesn't work.
Do this rather:
article[data-color="#123456"] header {
background-color: "#123456";
}
article[data-color="#123456"] a {
color: "#123456";
}

Related

JavaScript/jQuery code optimization

I'm learning JavaScript and jQuery and currently I'm dealing with following code:
$("#hrefBlur0").hover(function() {
$("#imgBlur0").toggleClass("blur frame");
});
$("#hrefBlur1").hover(function() {
$("#imgBlur1").toggleClass("blur frame");
});
$("#hrefBlur2").hover(function() {
$("#imgBlur2").toggleClass("blur frame");
});
$("#hrefBlur3").hover(function() {
$("#imgBlur3").toggleClass("blur frame");
});
$("#hrefBlur4").hover(function() {
$("#imgBlur4").toggleClass("blur frame");
});
$("#hrefBlur5").hover(function() {
$("#imgBlur5").toggleClass("blur frame");
});
$("#hrefBlur6").hover(function() {
$("#imgBlur6").toggleClass("blur frame");
});
$("#hrefBlur7").hover(function() {
$("#imgBlur7").toggleClass("blur frame");
});
The code is supposed to remove blur effect from an image while I hoover a cursor on a href link on the website. I'm wondering if I can do it faster, with fewer lines of code.
I tried:
for (var i = 0; i < 8; i++) {
$("#hrefBlur" + i).hover(function() {
$("#imgBlur" + i).toggleClass("blur frame");
});
}
But that code doesn't work.
Here's the JS fiddle: link
You can set a class to the elements and select that class, for example let's say you want to use "blurMeContainer" for the container, you can do something like this:
$(".blurMeContainer").hover(function(el){
$(this).find("img").toggleClass("blur frame");
});
The trick is that you must be aware that jQuery applies the events to the element, so inside the events function, the "this" accessor is the element involved in the event, than you can use the $ function in the selector in order to have his corrispective jQuery element, and then you can use "find" method to find any img tag inside the jQuery element. Obviously this could work only if you have a single image in the container, if you need to identify only one image in a set of images inside a single container, assign a class to that image (IE: "blurMe") and change the code in this way:
$(".blurMeContainer").hover(function(el){
$(this).find(".blurMe").toggleClass("blur frame");
});
Use attributeStartsWith selector , that Selects elements that have the specified attribute with a value beginning exactly with a given string:
$('a[id^="hrefBlur"]').hover(function() {
$(this).find('img').toggleClass("blur frame");
});
Here's working fiddle
Although doing what your after can be done with JQuery. I personally think it's the wrong tool for the Job.
CSS, will do all this for you, in a much simpler way. No Javascript needed. With the added benefit of the browser optimisations.
.blurme {
filter: blur(3px);
cursor: pointer;
transition: color 2s, filter 1s;
}
.blurme:hover {
filter: none;
color: red;
font-weight: bold;
}
<span class="blurme">One</span>
<span class="blurme">Two</span>
<span class="blurme">Three</span>
<span class="blurme">Four</span>
<span class="blurme">Five</span>
<span class="blurme">Six</span>
<br>
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">

How to change CSS pseudo-class element using JavaScript

I want to change this image using javascript:
dance:active { background-image: url("myImage.png") }
You can use
document.getElementById(element).style.backgroundImage = url(image);
to change
#element {background-image: url(image)}
I would like to change the image of when the element is active using javascript. Thanks!
I figured it out!
You can have multiple classes in your CSS :
element.dance1 { stuff }
element.dance1:active { active stuff }
element.dance2 { stuff 2 }
element.dance2:active { active stuff 2 }
and then change the class of the element in javascript:
document.getElementById(element).className = dance1/dance2
You can try using jQuery to achive what you want. dance: active is CSS Pseudo-classes. Learn more about Pseudo-class.
The demo change the div color when mouse down and switch the color back when mouse up. Leave comments if this is not what you want.
$("#dance").on("mousedown", function () {
$("#dance").css("background", "blue");
}).on("mouseup", function(){
$("#dance").css("background", "black");
});
https://jsfiddle.net/x_li/5nkvms8q/
and jQuery can also do the following
$('#damce:checked').val();

Replace "inline style" with a "css class" depending by value of its inline style

My site has CMS, so users can directly insert texts and images. CMS ui allows to float left/right images, applying an inline style to IMG tags.
<img src='...' style='float:left'>
I would like to detect when an IMG has a float:left/right style and replace it with a class in order to declare more properties for it like the following example:
.floated-left
{
float:left;
margin-right:20px;
border-left:solid 5px red;
....
}
I thought about something like this:
if ( $("article").find('img').css('float') == 'left')
{
this.addClass('floated-left');
}
But seems that "if clause" never be true. (I know that probably also this.addClass() is wrong, but neither alert() is never fired at the moment)
Can you help me?
Use attr instead of css for selecting inline styled objects:
$('article img').each(function() {
if ( $(this).attr('style') == 'float:left') {
$(this).removeAttr('style').addClass('floated-left');
}
});
if some of object's style is different, try this way:
$('article img').each(function() {
if ( $(this).attr('style').indexOf('float:left') > -1 ) {
var targetedStyle = $(this).attr('style').replace('float:left','');
$(this).attr('style',targetedStyle).addClass('floated-left');
}
});
In order to apply more declarations, you could simply achieve that by pure CSS:
img[style*="float:left"],
img[style*="float: left"] {
margin-right : 20px;
border-left : solid 5px red;
}
You could play with CSS attribute selectors to select the valid image/element.

how do I modify a :hover style using JavaScript / jQuery?

I have a :hover style definition declared in the CSS stylesheet file:
.myclass:hover {
border-color: red;
background-image: url('http://goo.gl/zdLfy');
}
Now, under given conditions, I want to change the background-image for this hover style.
I don't know how to do this using JavaScript / jQuery. Is this possible? How?
You can add a new style tag cascade over the previous declaration. assuming the css in in the head tag
$('head').append('<style>#element:hover {/
background-image: url("http://new.image/url");/
}/
<style>');
$('#element').hover(function() {
//on hover
if(condition === true) {
$(this).addClass('newBGImage');
}
}, function() {
//when hover ends
if($(this).hasClass('newBGImage')) {
$(this).removeClass('newBGImage');
}
});
Make your CSS be something like this:
.myclass:hover {
border-color: red;
background-image: url('http://goo.gl/zdLfy');
}
.specialCondition:hover {
background-image: url('http://anotherURL');
}
And then, for that special condition do:
$('.myclass').addClass('specialCondition');
And when the special condition is no longer there, remove the class:
$('.myclass').removeClass('specialCondition');
This way you keep your background-urls where they belong, in the CSS
You want to add a class that has the new background and then on hover use something like
$(this).addClass("YourClassName");
and then on leave
$(this).removeClass("YourClassName");

change a different div's class on mouseover

There's many examples of this but I can't find the right one for me - I believe mine is a more simple example.
I have as follows:
<li onmouseover="this.className='change-here2'" onmouseout="this.className='change-here'">
<div class="change-here">
Text Here
</div>
</li>
The li element has a background image, and a hover effect that changes the background image.
Using this.className changes the li class, when what I want is to change the div below it's class.
Shouldn't I be able to modify this to div.change-here, or something similar? I don't know the syntax...
Any help is appreciated.
EDIT: TimWolla's solution works brilliantly. Thank you all.
Why don't you use CSS only?
li .class { background-color: red; }
li:hover .class { background-color: green; }
See: http://jsfiddle.net/TimWolla/zp2td/
Can you do something to the affect of $(this).children(':first').addClass('change-here'); for that?
May I suggest:
var lis = document.getElementsByTagName('li');
for (var i=0, len=lis.length; i<len; i++){
lis[i].onmouseover = function(){
var firstDiv = this.getElementsByTagName('div')[0];
firstDiv.className = 'change-here';
};
lis[i].onmouseout = function(){
var firstDiv = this.getElementsByTagName('div')[0];
firstDiv.className = '';
};
}
JS Fiddle demo.
The reason I'm taking this approach, rather than using the in-line onmouseover attribute, is to make it somewhat easier to adapt in the case of the requirements changing at a later date. Also, it's slightly less 'intrusive' this way, and leaves the html somewhat easier to read. It is, of course a personal preference, though.
It's worth noting that the CSS-approach, as mentioned by TimWolla is far more sensible than involving JavaScript.
Updated answer to incorporate all the suggestions
<style>
.div_1 {
color: #F00;
}
.div_2 {
color: #0F0;
}
</style>
<li onMouseOver="this.childNodes[0].className = 'div_1';" onMouseOut="this.childNodes[0].className = 'div_2';">
<div class="div_1">
Text Here
</div>
</li>
This should work:
this.childNodes[0].className = 'change-here';

Categories