3

I have a div that looks something like this:

<p class="stepNode" aria-disabled="true" style="background: url(https://...jpg) 50% 50%;">
    <p class="stepLabel">
       <div> New Step</div>
     </p>
</p>

I want to rotate the background image within the div 90 degrees counterclockwise (without rotating the entire container ".stepNode". How can I do this using jQuery?

scientiffic
  • 9,045
  • 18
  • 76
  • 149

2 Answers2

2

You can add a :before to a container which contains the background (See this for more information).

.stepNode:before {
    content: "";
    position: absolute;
    width: 200%;
    height: 200%;
    top: -50%;
    left: -50%;
    z-index: -1;
    background: url(some-background-url-here) 40% 50% no-repeat; 

Then you make a css class that contains the rotate properties.

.transform:before {
    -webkit-transform: rotate(-30deg);
    -moz-transform: rotate(-30deg);
    -ms-transform: rotate(-30deg);
    -o-transform: rotate(-30deg);
    transform: rotate(-30deg);
}

And via jquery, you can add the class:

$(".stepNode").addClass("transform");

Also, you can set a transition time, to add animation (put this in .stepNode:before)

-webkit-transition: all 1s;
-moz-transition: all 1s;
-ms-transition: all 1s
-o-transition: all 1s;
transition: all 1s;

Here is a working jsfiddle.

Edit: 90 degrees version: jsfiddle

Yatoom
  • 307
  • 1
  • 15
  • thanks for your help. I'm trying this out, but I need to set the background of the :before element dynamically. any ideas? – scientiffic Jul 19 '14 at 17:07
  • 1
    Normally you would select the element and use $(selector).css(). But since we are using the pseudo-element, which is not part of the DOM, we can't select it with jQuery. So, instead, you can use $("head").append() to directly add css to the html. Check the [Updated jsfiddle](http://jsfiddle.net/q85k6/2/). – Yatoom Jul 19 '14 at 17:46
1

In order to achieve this, you would need to have two divs which are in absolute positioning. In containing the background image and one containing the text.

<div class="myRotate"></div>
<div class="myContent">
    <p class="stepNode" aria-disabled="true">
        <p class="stepLabel">
           <div> New Step</div>
        </p>
    </p>
</div>

Next you could attach a Jquery OnClick event on whatever element you want in order for the background to rotate.

$(function(){
    $('.myContent').click(function(){
        $('.myRotate').css({'-webkit-transform' : 'rotate(-90deg)',
                     '-moz-transform' : 'rotate(-90deg)',
                     '-ms-transform' : 'rotate(-90deg)',
                     'transform' : 'rotate(-90deg)'});
    });
});

Here is a working example

IndieRok
  • 1,778
  • 1
  • 14
  • 21