pjldesign
pjldesign

Reputation: 397

Add class name only, conditonally

I am using a plugin which determines the brightness of a div's background-color and dynamically applies a "light" or "dark" class to it. I'm trying to grab that class and apply it to another div in order to style it based on the returned value.

var topbar = $(".top-bar");
if ($(".quote-block").is( "dark" ) ) {
    topbar.addClass('background--dark');
};
if ($(".quote-block").is( "light" ) ) {
    topbar.addClass('background--light');
};

To streamline this however, it would be ideal to return just the class name alone and append it to the "background--" (i.e.: "background--" plus the "dark" class yielded by plugin, resulting in .background--dark). How can I achieve this with JQ? Clearly I am a novice so any insight would be greatly appreciated.

This is the intended structure:

<nav class="top-bar"></nav>
<div class="main-content">
    <section class="quote-block light<--dynamic class"></section>
    <section class="quote-block dark<--dynamic class"></section>
</div>

Upvotes: 0

Views: 61

Answers (1)

Andy Hoffman
Andy Hoffman

Reputation: 19111

I'm making this up because there was no HTML supplied in your question. Hopefully this can still help you.

function getLight() {
  var prefix = "background--";
  
  return $(".quote-block").hasClass("dark") ? (prefix + "dark") : 
         $(".quote-block").hasClass("light") ? (prefix + "light") : "";   							
}

$(".top-bar").addClass(getLight());
div {
  height: 2em;
}

.background--dark {
  background: black;
  border: 1px solid white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="top-bar"></div>
<div class="quote-block dark"></div>

Upvotes: 1

Related Questions