zoosrc zoosrc - 1 month ago 8
Sass (Sass) Question

Sass 'if' statement based on existing class

I'm new to Sass and would like to use the 'if' statement to detect an existing class on an element in order to generate the relevant css.

My setup has a large number of Javascript generated images, which are assigned a unique ID, as well as a class of "picture" and a randomly assigned class of either top, right, bottom or left.

I am also using a random function for Sass (found here: https://gist.github.com/chriseppstein/1561650), and would like a different value assigned to each ID, so that each element is randomly positioned.

My SCSS has the following, which positions the images based on which class it was assigned:

@for $i from 0 through $number-of-pictures {
#picture-#{$i}{

&.top {
left: random($stage-width);
}

&.right {
top: random($stage-height);
}

&.bottom {
left: random($stage-width);
}

&.left {
top: random($stage-height);
}
}
}


This works well, but creates a ton of unused declaration blocks. For example, #picture-38 was assigned the class ".top", so all I need is the first declaration block, but the CSS exports all the options:

#picture-38.top {
left: 38px; //This is a random number that is different for each ID.
}
#picture-38.right {
top: 28px;
}
#picture-38.bottom {
left: 12px;
}
#picture-38.left {
top: 47px;
}


What I need is an if statement, that detects if the element has a class before parsing the css. Something like:

@if "#picture-#{$i} has class $class-top" {
&.top {
left: random($stage-width);
}
}


Any ideas?

Answer

The answer is you cannot do this with SASS/SCSS.

You are trying to detect the possession/assignment of a class to a DOM element.

The way to interact with DOM elements is JavaScript

What you need to do is use JavaScript to detect if "picture-x#" has class "class-top" and then set a random top value accordingly.

E.g.

var picture = document.GetElementById('picture-1');
var pic_class = picture.className
if(pic_class.indexOf('class-top') != -1)
{
    /*Returns a random number between 1 and 100*/
    picture.style.top = Math.floor((Math.random()*100)+1) + 'px';
}

Sidenote: top requires a unit of measurement (e.g. px), hence the + 'px'