Paul Paul - 21 days ago 4
CSS Question

How to style an image created using javaScript

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.

Answer

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");

Comments