Pascal Pascal - 1 year ago 72
Javascript Question

Two events by clicking and reclicking on a div tag

I want to change the color from black to orange by clicking on an element and change the color from orange to black when I click on the element again.

I did also an element:hover selector in CSS so the icon turns to orange when hovered.

With my code, the element turns to orange when hovered and change to orange when clicked on it. It also changes back to black when I click on it again. But once I clicked on it, the hover selector doesnt work anymore. So when I clicked twice on it, it stays black by hovering.

My HTML code

<div id="activitys">
<div class="pictures_activitys"></div>

My javascript code

$( document ).ready(function() {
var jogging_selected = false;

$( ".pictures_activitys:nth-child(1)" ).click(function () {

$(".pictures_activitys:nth-child(1)").css( "background", "url(img/sports/jogging_black.png)" );
$(".pictures_activitys:nth-child(1)").css( "background", "url(img/sports/jogging_orange.png)" );

jogging_selected = !jogging_selected;


My CSS code:

margin: 30px;
margin-top: 80px;
width: 128px;
height: 128px;
cursor: pointer;

Someone can tell me why the element stops turning orange by hovering when i clicked twice on it?

Answer Source

Add !important to your background on hover

    background:url(../img/sports/jogging_orange.png) !important;
    cursor: pointer;

because your script made inline style to the element so this inline style override you css so !important will force element to get the background form css and override the inline style

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download