Reputation: 1327
Thanks to Stack Overflow I managed to solve an issue I was having with inconsistent transitions by preloading an image using javaScript.
To skip over what is working I won't post all the code. In short, I have an image on my HTML and a button that when clicked triggers a transition in which another image takes its place with a slide down. The inconsistencies I was getting got solved by creating the img in my javascript (as it gets loaded faster that way). I then apply some classes that perform the transition. Here is the relevant code:
HTML
<div class="page page-1"><img src="myFirstImage.jpg" width="100%"></div>
<div id="myDiv"class="page page-2"></div>
CSS
.page {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
overflow: hidden;
display: block;
}
.page img {
min-height: 100%;
}
.pt-page-moveFromTop {
-webkit-animation: moveFromTop 2s ease both;
animation: moveFromTop 2s ease both;
}
.pt-page-moveToBottom {
-webkit-animation: moveToBottom 2s ease both;
animation: moveToBottom 2s ease both;
}
@keyframes moveFromTop {
from { -webkit-transform: translateY(-100%); transform: translateY(-100%); }
}
@keyframes moveToBottom {
from { }
to { -webkit-transform: translateY(100%); transform: translateY(100%); }
}
javaScript
var image2 = new Image();
image2.src = "mySecondImg.jpg";
$(document).ready( function () {
$('.myButton').click(function(){
$('.page-1').addClass('pt-page-moveToBottom');
$('.page-2').append(image2);
$('.page-2').addClass('pt-page-moveFromTop');
});
});
It all works, but my second image doesn't get styled with the classes "page" and "page-2". So my question is, how can I apply those styles to the image() I created in js. I've tried something like
image2.addClass("page page-2");
But that doesn't do it. What is the best way to accomplish this? Thanks for your time.
Upvotes: 1
Views: 1694
Reputation: 722
Since you used
var image2 = new Image();
image2.src = "mySecondImg.jpg";
then I guess you may want to use a pure JS solution until the end. Then, you can assign the image class using:
image2.className = "className";
or add another class name like this:
image2.className += " className"; //with a space before
Upvotes: 1
Reputation: 11301
$('.page-2').addClass('pt-page-moveFromTop');
adds class to img container, not to img
itself. You should do $('.page-2 img').addClass('pt-page-moveFromTop');
instead.
Upvotes: 0
Reputation: 2975
you are mixing javascript and jquery here. The add class function will only work with a jquery element.
You should be doing someting like $(image2).addClass("page page-2");
Upvotes: 1