Léo Kaj Cbnns
Léo Kaj Cbnns

Reputation: 105

Triggering an animation on a div by clicking a button using addClass/removeClass with Javascript

So I'm trying to trigger an animation by clicking on a button using addClass and removeClass with Javascript.

I'm not bad at HTML/CSS but I only strating to learn Javascript by editing snipets.

So here's mine can you tell me why my div won't rotate when I click the black button ?

Thanks in advance !

<button class="menu-circle"></button>

<img class='imgblock' src="http://lorempixel.com/400/200/" alt="" />

.menu-circle {
height: 100px;
width: 100px;
background-color: #000000;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
transition: .1s;
z-index: 100;
border: none;
}

.menu-circle:hover {
height: 115px;
width: 115px;
}

.menu-circle:active {
height: 100px;
width: 100px;
}

.imgblock {
display: block;
margin: 20px;
-webkit-transition-duration: 1s;
-moz-transition-duration: 1s;
-o-transition-duration: 1s;
transition-duration: 1s;
}

.rotate {
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
}

$('.menu-circle').on('click', function(){
$('img .imgblock').addClass('rotate');
$('img .imgblock .rotate').removeClass('rotate');
});

WORKING FIDDLE :

http://jsfiddle.net/leokaj/rv5PR/366/

Upvotes: 0

Views: 932

Answers (3)

alynioke
alynioke

Reputation: 210

You have several problems with your fiddle:

  1. Wrong class names: in js $('.menucircle') and in html - class="menu-circle"
  2. You don't need space between img and class in jquery selector $('img .imgblock') - space means you're looking for .imgblock class inside the img tag (which is impossible).
  3. .current class is not defined nor in html, nor in css, but appear in js

Here's fiddle where I fixed the problems and which works: DEMO

JS:

$('.menu-circle').on('click', function(){
    var $img = $('.crossRotate');
    if (!$img.hasClass('rotate')) {
        $img.addClass('rotate');
    } else {
        $img.removeClass('rotate');
    }
});

Upvotes: 2

Andrew Aitken
Andrew Aitken

Reputation: 681

As you seem to be trying to make it jiggle a bit in animation and you're using jQuery already then I would say you need to look at the .animate() method of teh jQuery library

https://api.jquery.com/animate/

Upvotes: 0

Vanojx1
Vanojx1

Reputation: 5574

You ve to manage this with 2 different events to animate the image

$('.menu-circle').on('mousedown', function(){
    $('.imgblock').addClass('rotate');  
});

$('.menu-circle').on('mouseup', function(){
    $('.imgblock').removeClass('rotate');
});

fiddle http://jsfiddle.net/3ehcuky5/

if you want to keep the image rotated or not the @alynioke solution is good

Upvotes: 0

Related Questions