0

I have a simple drop-down menu, which is opened by a triangle (caret) symbol. I need to rotate caret upside-down (180 degrees), when the menu is opened, and go back to default position, when it is closed back. Ideal is to achieve this without engaging css classes, which would be the most commonly suggested solution, when I was looking up for the answer.

I have tried to use ternary operator on click, like this:

    $(this).css('transform', ($(this).css('transform') == 'rotate(180deg)') ? 'none' : 'rotate(180deg)');

But it won't work; it rotates once - upside down - but does not go back to default position on next click. I have tried also with 'rotate(0deg)' and 'rotate(360deg)', same effect (no effect actually). What statement should I use instead?

Lafioka
  • 5
  • 1
  • 4

3 Answers3

0

Try it like the answer here jQuery toggle CSS? Using Jquery toggle. Although I'm not sure why you're avoiding CSS classes, that would make it super easy.

Community
  • 1
  • 1
garek007
  • 395
  • 4
  • 15
0

css('transform') has it's own timeline. the first time ran, it reached to end of the timeline. You can't expect it to restart the timeline again.

What I've been found out is that, you could.. "Rather hacky", add timeout to the statement. when timeout initiated (even timer is 0ms), the css will refresh and take a second change of the css property once again.

That's the reason why people did it in JS to add css classes. because when you add or remove a css class. You simply force browser to re-render, so the timeline of that css property got reset.

0

As described in the documentation the value of transform property is not rotate....

Because you need only toggle between rotate and not you can change the test from :

$(this).css('transform', ($(this).css('transform') == 'rotate(180deg)') ? 'none' : 'rotate(180deg)');

to:

$(this).css('transform', ($(this).css('transform') == 'none') ? 'rotate(20deg)' : 'none');

An example:

$('p').on('click', function(e) {
    console.log($(this).css('transform'));
    $(this).css('transform', ($(this).css('transform') == 'none') ? 'rotate(180deg)' : 'none');
})
p {
    border: solid red;
    margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<p>Transformed element</p>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61