Jonathan Jonathan - 2 months ago 8
Javascript Question

Toggle background on an off in a div by clickin on it

I've been trying to find a javascript/jquery that makes it possible to toggle the background on and off on multiple divs.

I'm creating a website with a menu where I want to be able to highlight dishes by clicking on them. Also I want it to work on phone, tablet and browser.

See fiddle

.menu-wrapper


I've been trying some scripts and modifying things that I've found, but since I lack the knowledge i need some help.

Thank you!

Answer

Some CSS:

.bg-red {
  background:red;
}

Some JavaScript

$('.menu-wrapper').on('click', function(){
    $(this).toggleClass('bg-red');
});

And you get this

$('.menu-wrapper').on('click', function(){
	$(this).toggleClass('bg-red');
});
.full-wrapper {
    width: 100%;
    height: 100%;
}

.menu-wrapper {
    height: 2em;
    width: 24em;
    background: #fff;
    text-align: center;
    line-height: 30px;
    margin: 10px auto;
}
.bg-red {
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="full-wrapper">
    <div class="menu-wrapper">Click and toggle background between red and white</div>
        <div class="menu-wrapper">Click and toggle background between red and white</div>
            <div class="menu-wrapper">Click and toggle background between red and white</div>
                <div class="menu-wrapper">Click and toggle background between red and white</div>
                    <div class="menu-wrapper">Click and toggle background between red and white</div>
                        <div class="menu-wrapper">Click and toggle background between red and white</div>
</div>