Lucifer N.
Lucifer N.

Reputation: 1056

Best way to change a CSS value using JS?

So I am styling a dropzone for a site. When a user drops an image, I want there to be a box-shadow on the preview element. If it is not an image I do not want the box shadow. The styling for the preview element in the css file looks like this:

 .dropzone .dz-preview,
 .dropzone-previews .dz-preview {
  background: transparent;
  position: relative;
  display: inline-block;
  margin: 40px;
  vertical-align: top;
  border: 1px solid transparent;
  padding: 10px 13px 10px 10px;
}

In my JS (inline) I already have a function set that will emit a certain thumbnail if the file is NOT an image:

mydropzone.on("addedfile", function(file) {
  if (!file.type.match(/image.*/)) {
    mydropzone.emit("thumbnail", file, "http://i.local.dev:5000/jLNutaV.png");
  }
});

I was thinking I could just do an else and set the box shadow, but I don't know how to set style for elements like the one in my CSS where several classnames are used. I just want this to be added to the CSS:

-webkit-box-shadow: 1px 1px 4px rgba(0,0,0,0.16);
box-shadow: 1px 1px 4px rgba(0,0,0,0.16);

Thanks

Upvotes: 1

Views: 109

Answers (1)

jfriend00
jfriend00

Reputation: 707158

One of the easiest ways to add or remove a set of CSS styles from an element is to create a CSS rule for those styles for a particular class name and then add/remove that class name to your particular element. If you want the styles added to your element, you add the class name to the element. If you want the styles removed, you remove that class name. Just use a unique class name that is just for this purpose so there are no unintended consequences to adding/removing this class name.

Keep in mind that class names are treated separately so you can have N other class names already on the object and you can then add or remove one particular class name and styles linked to that class name will change while the others don't change.

CSS rule:

.dropzoneHighlight {
    -webkit-box-shadow: 1px 1px 4px rgba(0,0,0,0.16);
    box-shadow: 1px 1px 4px rgba(0,0,0,0.16);
}

Javascript:

if (condition met) {
    addClass(myElement, "dropzoneHighlight");
}

function addClass(elem, cls) {
    elem.className += (" " + cls);
}

function removeClass(elem, cls) {
    var str = " " + elem.className + " ";
    elem.className = str.replace(" " + cls + " ", " ").replace(/^\s+|\s+$/g, "");
}

Upvotes: 3

Related Questions