css3 animation only happening once - javascript

I'm trying to make a box rotate through javascript/css3 rotate every time I click on it. It works, but only the first time I click on it. Each time after, I get the alert which means it's not a javascript error - but no animation.
Here is my simple page -
<script>
function rotate( box )
{
alert('start');
box.style.webkitTransform = 'rotate(360deg)';
}
</script>
<style>
#box{ height:100px; width:100px; border:1px solid red; -webkit-transition: -webkit-transform 1s ease-out; }
</style>
<div id='box' onclick='rotate(this);'></div>
I figured there needs to be something I need to put after the rotate() to tell it to go back to the beginning stage so that it can rotate 360 again.

Edit: Assuming you want it to be completely CSS:
Webkit transitions are currently being tested and are very rough. Especially for what you want to do. Since these are "transformations", and the style string is quite complex, it creates a nasty challenge.
The best thing to do it to reverse the rotation every other click:
<script>
function rotate( box )
{
box.style.webkitTransform = box.style.webkitTransform == "rotate(360deg)" ? "rotate(0deg)" : "rotate(360deg)";
}
</script>
<style>
#box{ height:100px; width:100px; border:1px solid red; -webkit-transition: -webkit-transform 1s ease-out; }
</style>
<div id='box' onclick='rotate(this);'></div>
Or youll have to deal with alot of dangerous coding, or javascript alternatives.

I reuse a script i made previously. It should now support Mozilla too.
<!-- head part -->
<script type="text/javascript">
var angle = 0; //Current rotation angle
var nbSteps = 30; //More steps is more fluid
var speed = 1000; //Time to make one rotation (ms)
var count = 0; //Count the nb of movement (0..nbSteps-1)
var element = null;
/**
* Rotate the element passed
*/
function rotate(box) {
if(count == 0) {
element = box;
rotateLoop();
}
}
/**
* Recursive method that rotate step by step
*/
function rotateLoop() {
angle-=360/nbSteps;
setElementAngle(angle);
count++;
if(count < nbSteps) {
setTimeout("rotateLoop()",speed/nbSteps);
}
else {
count=0;
setElementAngle(0); //Just to be sure
}
}
/**
* Use for the rotation
*/
function setElementAngle(angle) {
var rotationStyle = "rotate(" + (360-angle) + "deg)";
element.style.WebkitTransform = rotationStyle;
element.style.MozTransform = rotationStyle;
element.style.OTransform = rotationStyle;
}
</script>
<style>
#box{
height:100px;
width:100px;
border:1px solid red;
}
</style>
<!-- body part -->
<div id='box' onclick="rotate(this);"></div>

Related

Pure Javascript alternatives to toggling a CSS class?

My goal is to rotate a div 180deg on each click, without toggling CSS classes.
I can achieve one rotation with the first click (.style.transform =
"rotate(180deg)";), but any subsequent click has no effect.
BTW, why exactly is that? The div's Id hasn't changed, so, in theory, the same trigger (a click, in this case) should call the same function, right? But it doesn't. I wonder what's the logic here, what's the technical explanation, and, moving to practice, how can I further manipulate this post-div (that is, the original div after its JavaScript manipulation) -- again, without toggling CSS classes.
function rotate() {
document.getElementById("container").style.transform =
"rotate(180deg)";
}
.container {
width: 200px;
height: 400px;
border: 5px solid;
border-bottom-color: blue;
border-top-color: red;
}
<div class="container" id="container" onclick="rotate()"></div>
The first time you change the transformation from "" to "rotate(180deg)", so it rotates.
Subsequent times you change it from "rotate(180deg)" to "rotate(180deg)" … which isn't a change at all, so nothing happens.
If you want to change it, then you need to actually assign a different value to it.
e.g.
const style = document.getElementById("container").style;
if (style.transform) {
style.transform = "";
} else {
style.transform = "rotate(180deg)";
}
Toggling a class is simpler, and clearer.
document.querySelector("#container").addEventListener("click", e => e.currentTarget.classList.toggle("rotated"));
.container {
width: 200px;
height: 400px;
border: 5px solid;
border-bottom-color: blue;
border-top-color: red;
transition: transform 0.25s;
}
.rotated {
transform: rotate(180deg);
}
<div class="container" id="container"></div>
You need to check the transform value and then rotate it anti-clockwise.
Here is the code:
HTML
<div class="container" id="container" onclick="rotate()"></div>
CSS
.container {
width: 200px;
height: 400px;
border: 5px solid;
border-bottom-color: blue;
border-top-color: red;
}
JS
function rotate() {
document.getElementById("container").style.transform =
document.getElementById("container").style.transform ===
"rotate(180deg)" ? "rotate(0deg)" : "rotate(180deg)";
}
Here is an example in codepen
The reason why the div is not rotating after first function call is that you are setting the transform style property to constant value (180deg). After first call the transform is performed and all following calls set transform to exactly the same value. In order to make it work, you have to increment rotate property each time you call the function.
In example:
let rotation = 0;
function rotate() {
document.getElementById("container").style.transform = `rotate(${rotation}deg)`;
rotation = (rotation + 180) % 360;
}
I made a fiddle , but basically, you can't rotate for the same value. Of course this is very raw, but prove the concept for you to understand. You can do it more programatically of course.
document.getElementById('container').addEventListener('click', function () {
this.style.transform = this.style.transform == "rotate(180deg)" ? "rotate(-90deg)" : "rotate(180deg)";
}
);
You can check this out: tutorial
<script>
var degrees = 0;
function rotate() {
if(degrees == 180){
document.getElementById("container").style.transform =
"rotate(360deg)";
degrees= 0;
}else{
document.getElementById("container").style.transform =
"rotate(180deg)";
degrees= 180;
}
}
</script>
Clearly is not optimized but could help you.
JSFiddle here
Others have answered your question already, so I will provide with an example to make your code a little bit more dynamic.
/**
* Rotate an <element> with a certain angle <rotateBy>
* 'this' is a reference to itself, which is passed by as an argument from the HTML.
* Change '180' in the method call to whatever to have it rotate differently.
*/
function rotate(element, rotateBy) {
var currentRotation = element.rotation || 0; // default to zero if not existing
newRotation = rotateBy + currentRotation;
element.rotation = newRotation; // store the property in the element
element.style.transform = "rotate(" + newRotation + "deg)";
}
.container {
width: 200px;
height: 400px;
border: 5px solid;
border-bottom-color: blue;
border-top-color: red;
transition: transform 400ms;
}
<div class="container" onclick="rotate(this, 180)"
></div>

how to make a div slide in from outside of the window, on load (javascript)?

My question pretty basic, it's written up there.
How to make a div slide in from outside of the window onload? For example, it may appear from the right side of the window.
And I actually need basic javascript code, not jQuery.
Thank you
You can do it in pure javascript also.
Create a timer interval. that runs every 1 ms. which modifies the left attribute every time the timer is hit. once the left reaches 0 stop the timer.
--html
var div = document.getElementById("slidingDiv");
div.style.position = "absolute";
var left = document.body.offsetWidth;
div.style.left = left + "px";
var gap = 5;
var timer = window.setInterval(function() {
div.style.left = left + "px";
if (left - gap < 0) {
left = 0;
} else {
left -= gap;
}
if (left == 0) {
clearInterval(timer);
}
}, 1);
<div>
<div id="slidingDiv">this div slides</div>
</div>
watch a demo in this fiddler.
This forum is not for code requests...
Anyway you can position a html element by using its offsetHeight and offsetWidth properties in javascript.
Also you have to use an interval to make the animation.
var target = document.getElementById('div');
var interval = window.setInterval(function () {
target.offsetWidth++;
// When the div moved enough...
if (target.offsetWidth > 300) {
window.clearInterval(interval); // ...clear the interval
}
}, 500); // The animation step will be done every 500ms -> 0.5s
When you are targeting new Browsers (IE9+) you can also look at css transitions with hardware acceleration, which is done like that:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.hw-ac {
transform: translate3d(0, 0, 0); /* This neat css rule says that the html element will be rendered from the GPU */
transition: left 1s linear; /* The animation will take 1 second */
}
.start-pos { /* The start position outside of the screen */
position: absolute;
left: -100px;
}
.target-pos { /* The target poition */
position: absolute;
left: 200px;
}
</style>
</head>
<body>
<div id="div" class="hw-ac start-pos">
</div>
</body>
</html>
Now with javascript just replace the class start-pos with the class target-pos:
var target = document.getElementById('div');
target.className = 'hw-ac target-pos';
Here an example for Firefox:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#div {
position: absolute;
background-color: #f00;
width: 50px;
height: 50px;
}
.hw-ac {
-moz-transform: translate3d(0, 0, 0); /* This neat css rule says that the html element will be rendered from the GPU */
-moz-transition: left 1s linear; /* The animation will take 1 second */
}
.start-pos { /* The start position outside of the screen */
left: -100px;
}
.target-pos { /* The target poition */
left: 200px;
}
</style>
</head>
<body>
<div id="div" class="hw-ac start-pos">
</div>
<script type="text/javascript">
function start() {
var target = document.getElementById('div');
target.className = 'hw-ac target-pos';
}
</script>
<input type="button" onclick="start();" value="PRESS ME" />
</body>
</html>

Changing background image - javascript

I would like to change a background image with JavaScript.
JS:
<head>
<script type="text/javascript">
// Ta funkcja odpowiedzialna jest odpowiedzialna za zmiane obrazow w tle
$(window).load(function(){
var i = 0;
var images = ['images/1.jpg','images/2.jpg','images/3.jpg','images/4.jpg','images/5.jpg'];
var image = $('#slideit');
image.css('background-image', 'url(images/1.jpg)');
image.css('background-size', 'cover');
setInterval(function(){
image.css('background-image', 'url(' + images [i++] +')');
// image.fadeOut(1500, function (){
// image.fadeIn(1000);
// })
if(i == images.length) i = 0;
}, 6000);
});
</script>
</head>
HTML:
<body id="slideit" style="width:100%;height:100%;">
The problem is in making the images change smoothly. The commented out code makes everything in the website fade in and fade out except the background. Why is this happening? This code works but does not change the image smoothly. How can I fade the images in and out?
Unfortunately CSS does not support the animation (via transition) of background images. Why? Actually, I'm not sure why. But it's enough to know they don't. Javascript works directly by extending CSS functionality. In short, what you want to do can't be done with Javascript without writing a very convoluted piece of code designed at hacking its functionality.
There is an easy work around using jQuery, however, which will actually make your source less complex too. Make the body relative, add each individual background image to the bottom of your source (to make them load after everything else) inside a named wrapper. Let's go with #backgrounds.
<style>
body{
height:100%;
position:relative
}
#backgrounds img{
position:absolute;
z-index:1; // this is important
top:0;
left:0;
width:100%;
height:100%;
opacity:0;
display:none;
}
#wrapper{
position:relative;
z-index:3; // again, this is important
}
</style>
We set the z-index of the wrapper to be higher than that of the images so that our content is in front of them, thus giving the illusion the images are background images. Change position:absolute to position:fixed if you want a background-attachment:fixed effect. I'm assuming you want their widths and heights to be that of the viewport; change them to whatever if not. We set the images to display:none to stop them all loading when the page loads. Yuck!
<div id="wrapper">
all of your page are belong to us...
</div>
<div id="backgrounds">
<img src="background/one.jpg" alt="">
<img src="background/two.jpg" alt="">
<img src="background/three.jpg" alt="">
</div>
And then simply cycle through each image using a counter based on the number of images (so you can easily cut and paste more images in later without any effort):
$(function(){
var total = $('#backgrounds img').length;
var counter = 1;
function cycle(){
// Makes old backgrounds appear beneath new ones
$('#backgrounds img').css('z-index','1')
// Set it to display and opacity 0 so we get the effect
$('#backgrounds img:nth-child('+counter+')').css({'opacity':'0','display':'block','z-index':'2'})
// Fade the background in
$('#backgrounds img:nth-child('+counter+')').animate({'opacity':'1'},1500)
// increase the counter
counter++
// make sure we're working within the quantity of images we have
if( counter > total ){ counter = 1 }
}
cycle();
setInterval(function(){cycle()},6000);
})
Try
$(function() {
$.fx.interval = 3000;
(function cycleBgImage(elem, bgimg) {
elem.css("backgroundImage", bgimg).delay(3000, "fx")
.fadeTo(3000, 1, "linear", function() {
$(this).fadeTo(3000, 0, "linear", function() {
var img = $(this).css("backgroundImage").split(",")
, bgimg = img.concat(img[0]).splice(1).join(",");
cycleBgImage(elem, bgimg);
});
});
}($("#slideit")));
});
#slideit {
width: 100%;
height: 100%;
display: block;
opacity: 0.0;
background-color: #000;
background-image: url("http://lorempixel.com/400/400/cats/?1")
, url("http://lorempixel.com/400/400/animals/?2")
, url("http://lorempixel.com/400/400/nature/?3")
, url("http://lorempixel.com/400/400/technics/?4")
, url("http://lorempixel.com/400/400/city/?5");
background-size: cover, 0px, 0px, 0px;
-webkit-transition: background-image 3000ms linear;
-moz-transition: background-image 3000ms linear;
-ms-transition: background-image 3000ms linear;
-o-transition: background-image 3000ms linear;
transition: background-image 3000ms linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body id="slideit"></body>

How to fetch the background of DIV on a bottom layer with exact position using jQuery and CSS

I'm looking to make a page that has a background gradient that changes color every few seconds and blends between transitions. Now I want to apply this effect on the to the upper elements that are blocked by a element that has a solid background.
To give you a better example what I mean I have attached a simple mockup and hopefully your understand what I'm attempting to do, I'm open to suggestions.
(source: bybe.net)
The problem is obviously the block that contains the black background which any PNG transparent used would see black not the gradient.
I'll include sample code so far:
<body><!-- A Jquery script will be used to add CSS background, Easy stuff -->
<div class="blackbox">
<div class="logo"><img src="#" alt=""></div>
<hr class="h-line">
<div class="v-line"> </div>
</div>
So what I'm after is either:
A known jQuery method to obtain a background image but it needs to be able to refer of the position of the gradient so its inline with the background.
A better solution to getting this to work, please bare in mind that the page needs to be responsive so I could use other methods but since its responsive I can't think of any.
Since you ask for alternatives to jQuery solutions
You could play a little with margins and box-shadow and keyframe animations.
Something in this direction for the shape (depends on what you want to do with which part - add content ... and in what way you want it to be responsive):
html:
<div class="wrapper">
<div class="header"><img src="http://i.imgur.com/CUbOIxr.png" alt="Company name" /></div>
<div class="content"></div>
</div>
CSS:
body {
background:orange;
width:100%;
height:100%;
}
.wrapper {
width:40%;
height:90%;
border:30px solid #000;
border-right-width:100px;
border-bottom-width:100px;
}
.header {
width:100%;
border-bottom:10px solid transparent;
-webkit-box-shadow: 0 30px 0 #000;
-moz-box-shadow: 0 30px 0 #000;
box-shadow: 0 30px 0 #000;
}
.header img {
width:100%;
}
.content {
width:95%;
height:400px;
background-color:#000;
margin-top:30px;
}
DEMO
This way no javascript is needed. And for the background you can use a linear gradient and do all animations with css transitions or keyframe animations. You also need to play with the lengths and adjust the borders and box-shadows to your needs, maybe add some #media queries for the responsiveness.
Hope this helps you a little in the right direction =)
Update:
I hoped the gradients changing was the smaller problem ;-) Silly me, sorry.
I will elaborate my CSS-only suggestion for the animation, but you can choose a javascript slider for the background animation, if you don't like CSS3 solutions - although this is the hot stuff now ;-)
Ok. So, I would add some more fixed positioned elements with gradient backgrounds (layer1 and layer2).
To have something in this direction in the html now:
<div class="layer layer1"></div>
<div class="layer layer2"></div>
<div class="wrapper">
<div class="header">
<img src="http://newtpond.com/test/company-name.png" alt="Company name" />
</div>
<div class="content"></div>
</div>
and add a keyframe animation on them in CSS (here it is just with the -webkit vendor prefix [probably cause I am a lazy bum], but I hope you can get the idea, and could add the others):
body {
width:100%;
height:100%;
margin:0;
padding:0;
}
/* for the animation */
.layer {
position:fixed;
width:100%;
height:100%;
}
#-webkit-keyframes GoLayer1 {
0% {
opacity:1;
}
50% {
opacity:0;
}
100% {
opacity:1;
}
}
#-webkit-keyframes GoLayer2 {
0% {
opacity:0;
}
50% {
opacity:1;
}
100% {
opacity:0;
}
}
.layer1 {
background: -webkit-linear-gradient(bottom, rgb(43, 70, 94) 29%, rgb(194, 41, 41) 65%, rgb(155, 171, 38) 83%);
-webkit-animation: GoLayer1 5s infinite;
}
.layer2 {
background: -webkit-linear-gradient(bottom, rgb(225, 202, 230) 29%, rgb(39, 163, 194) 65%, rgb(36, 124, 171) 83%);
-webkit-animation: GoLayer2 5s infinite;
}
/* the wrapper shape */
.wrapper {
z-index:999;
opacity:1;
position:relative;
width:40%;
height:90%;
border:30px solid #000;
border-right-width:100px;
border-bottom-width:100px;
}
.header {
width:100%;
border-bottom:10px solid transparent;
-webkit-box-shadow: 0 30px 0 #000;
-moz-box-shadow: 0 30px 0 #000;
box-shadow: 0 30px 0 #000;
}
.header img {
width:100%;
}
.content {
width:95%;
height:400px;
background-color:#000;
margin-top:28px;
}
DEMO (tested in Chrome 26 - looked cool =)
This is now where I can point you according this CSS-only approach. There is still stuff to modify and consider browser compatibility. But it is certainly an alternative ... and a step in the direction where html5 and css3 is going (if you want to be hot and cool ;-), hehe, sorry, too much silliness.
Good luck!
Update 2:
So, I overcame my laziness a tiny bit and added some more vendor prefixes to the top example (and of course you can use any image as background):
DEMO
And here I add another example, that is using a png image for the gradient, and is sliding up and down in the background (as another alternative):
DEMO
There are many ways to do this, CSS3 and images are already suggested, so I'll suggest using a canvas.
The HTML canvas element has everything you need built in. It allows for gradient background fills, and with globalCompositeOperation, masking of shapes and text is possible, creating cut-outs in the background to make real changeable HTML elements truly transparent against a colored background. It also scales well, and can easily be made responsive.
The canvas element is supported in all major browsers except Internet Explorer 8 and below, which means browser support is better than many of the CSS3 methods previously mentioned, like keyframes and background-size.
Using a fallback, like say images that fade in and out if canvas is'nt available, should'nt be very hard to figure out, and in all other browsers except Internet Explorer below version 9, no images would be needed to create the gradient backgrounds and text masks in a canvas, which should make the loading of the page significantly faster.
To detect wether or not canvas is supported, you can use this convenient function :
function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
used like so :
if ( isCanvasSupported() ) {
// do canvas stuff
}else{
// fall back to images
}
So, lets get to it! To create a "last resort" fallback and some elements we can "clone" into the canvas, we'll create the elements we need in the HTML to get a structure somewhat similar to what you've outlined in your question. This has the added advantage of being able to just change some of the CSS to also make changes in the canvas :
<div id="gradient">
<div class="text">COMPANY NAME</div>
<div class="h_bar"></div>
<div class="v_bar"></div>
</div>
It's just a container with an element for text, and one for each of the bars.
Some styling is neccessary as well, I'll do it the easy way, with position absolute and some really fast positioning, as these elements won't be visible unless someone has disabled javascript anyway :
#gradient {position: absolute;
background: #000;
top: 5%; left: 5%; right: 5%; bottom: 5%;
}
.text {position: absolute;
top: 20px;
left: 100px;
width: 400px;
color: #fff; font-size: 40px; font-weight: bold;
font-family: arial, verdana, sans-serif;
}
.h_bar {position: absolute;
height: 20px;
top: 100px; left: 60px; right: 60px;
background: #fff;
}
.v_bar {position: absolute;
width: 20px;
top: 140px; bottom: 30px; right: 60px;
background: #fff;
}
Without any javascript that would look exactly like THIS FIDDLE, and it should be somewhat responsive and adapt to the window size.
Now we need some javascript to turn those elements into something in a canvas. We'll create two canvas elements, one for the background, as I've decided to animate the background continously between random gradients, and one for the inner black box and the content (the text and the bars).
As the masking of the text and bars can be a little slow, we don't have to redraw everything, just the background canvas, as the foreground is pretty static.
This also avoids a flickering issue in some browsers with high frame rates, and we're going to use requestAnimationFrame for the animation of the background canvas, so flickering in the text mask would be an issue if we did'nt use two canvas elements.
For browsers that does'nt support requestAnimationFrame we'll add this polyfill to make sure it works everywhere.
Time to write some javascript, this of course uses jQuery :
var gradSite = {
init: function() {
var self = this;
self.create().setSizes().events();
(function animationloop(){
requestAnimationFrame(animationloop);
self.draw().colors.generate();
})();
},
create: function() { // creates the canvas elements
this.canvas = document.createElement('canvas');
this.canvas2 = document.createElement('canvas');
this.canvas.id = 'canvas1';
this.canvas2.id = 'canvas2';
this.canvas.style.position = 'absolute';
this.canvas2.style.position = 'absolute';
$('#gradient').after(this.canvas, this.canvas2);
return this;
},
events: function() { //event handlers
$(window).on('resize', this.setSizes);
$('#gradient').on('contentchange', this.draw2);
return this;
},
setSizes: function() { // sets sizes on load and resize
var self = gradSite,
w = $(window),
m = $('#gradient');
self.canvas.height = w.height();
self.canvas.width = w.width();
self.canvas2.bg = m.css('background-color');
self.canvas2.height = m.height();
self.canvas2.width = m.width();
self.canvas2.style.top = m.offset().top + 'px';
self.canvas2.style.left = m.offset().left + 'px';
self.draw2();
return self;
},
colors: {
colors: {
0: [255,255,0],
1: [255,170,0],
2: [255,0,0]
},
map: {
0: [0,0,1],
1: [0,1,1],
2: [0,1,1]
},
generate: function() { // generates the random colors
var self = this;
$.each(self.colors, function(i,color) {
$.each(color, function(j, c) {
var r = Math.random(),
r2 = Math.random(),
val = self.map[i][j] == 0 ? (c-(j+r)) : (c+(j+r2));
if (c > 255) self.map[i][j] = 0;
if (c < 0 ) self.map[i][j] = 1;
self.colors[i][j] = val;
});
});
}
},
raf: (function() { // polyfill for requestAnimationFrame
var lastTime = 0,
vendors = ['webkit', 'moz'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}()),
calculateColor: function(colors) { // returns a rgb color from the array
return 'rgb(' + Math.round(colors[0]) + ',' + Math.round(colors[1]) + ',' + Math.round(colors[2]) + ')';
},
draw: function() { //draws the color background
var self = this,
c = self.canvas || document.getElementById('canvas1'),
ctx = c.getContext('2d'),
grad = ctx.createLinearGradient(0,0,0,self.canvas.height);
c.width = c.width;
grad.addColorStop(0, self.calculateColor(self.colors.colors[0]));
grad.addColorStop(0.5, self.calculateColor(self.colors.colors[1]));
grad.addColorStop(1, self.calculateColor(self.colors.colors[2]));
ctx.fillStyle = grad;
ctx.fillRect(0,0,self.canvas.width, self.canvas.height);
return self;
},
draw2: function() { // draws the black square and content
var self = this,
c = self.canvas2 || document.getElementById('canvas2'),
ctx2 = c.getContext('2d'),
txt = $('.text', '#gradient').first(),
hbar = $('.h_bar', '#gradient').first(),
vbar = $('.v_bar', '#gradient').first();
c.width = c.width;
ctx2.globalCompositeOperation = 'xor';
ctx2.font = txt.css('font');
ctx2.fillStyle = c.bg || '#000';
ctx2.fillText(txt.text(), txt.offset().left, txt.offset().top);
ctx2.fillRect(hbar.position().left, hbar.position().top, hbar.width(),hbar.height());
ctx2.fillRect(vbar.position().left, vbar.position().top, vbar.width(),vbar.height());
ctx2.fillRect(0,0,c.width,c.height);
}
}
The raf function would be the polyfill for requestAnimationFrame, and the two draw functions create the content in the canvas. It's really not that complicated.
We will call the above script inside a DOM ready handler, like so :
$(function() {
gradSite.init(); // starts the canvas stuff
});
Adding all that up into a fiddle, and adding a few elements for demonstration purposes, it would look like THIS FIDDLE, and here's the finished ->
FULL SCREEN DEMO
The only way I can see this working is if your black div has no background and is cut into sections that that each have a background. The company name area would need to have the same foreground color as the background for the rest of the div sections. Depending on your layout needs this might be fine.
For example, you could cut it into three sections and two images:
You can try combinig background-size and background-position with javascript:
setGradientSizes = function (el) {
var width = $(document).width() + 'px', height = $(document).height() + 'px';
$(el || '.gradient:not(body)').each(function () {
var offset = $(this).offset();
$(this).css('background-size', width + ' ' + height);
$(this).css('background-position', (offset.left * -1) + 'px ' + (offset.top * -1) + 'px');
})};
Working example here -> jsbin
NOTES:
this is not 100% cross browser - background-size is supported in FF4.0+, IE9.0+, Opera 10.0+, Chrome 1.0+, Safari 3+.
For some older browsers you can try browser specific prefixes (like -moz-background-size) - my example does not cover that.
To reduce load flickering you can apply calculations at first and then add background gradient
You could make the background of the image with the text black, then set the div's background color to rgba(0,0,0,0) making it transparent
This might be helpful for you according to my understanding
There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).
You will have to revert style changes manually:
div { color: green; }
form div { color: red; }
form div div.content { color: green; }
If you have access to the markup, you can add several classes to style precisely what you need:
form div.sub { color: red; }
form div div.content { /* remains green */ }
Edit: The CSS Working Group is up to something:
div.content {
all: default;
}
If I was you I'll duplicate the css and jQuery, print it on a div on top of what ever and make the overflow hidden (like masking layers but with z-index).

Overlay one div over another on click of a button

I have two visualizations, each in different div. I want to place one div over another on button click to overlay and compare them. Then, on another button click, I want to separate it out. Any code snippet or links would be appreciated. Right now I am just trying to make use of the following javascript function:
function ShowOverlay(divID, xCoordinate, yCoordinate) {
var divObject = document.getElementById(divID);
divObject.style.visibility = "visible";
divObject.style.left = xCoordinate;
divObject.style.top = yCoordinate;
}
you should use absolute or relative positioning.
If your position property is not set to absolute or relative style.left and style.top won't have any effect.
The following will allow them to move (you just need to work out the coordinates:
function ShowOverlay(divID, xCoordinate, yCoordinate) {
var divObject = document.getElementById(divID);
divObject.style.visibility = "visible";
divObject.style.left = xCoordinate;
divObject.style.top = yCoordinate;
divObject.style.position = "absolute";
}
To undo it, simple set position back to static:
divObject.style.position = "static";
Here is very simple working example of moving three div's over one another on button click.
HTML code
<div class="container">
<div class = "circlea"><h2>link</h2></div>
<div class = "circleb"><h2>link</h2></div>
<div class = "circlec"><h2>link</h2></div>
<button >click me</button>
</div>
.circlea,.circleb,.circlec{
height:150px;
width:150px;
border-radius:50%;
margin-left:50%;
margin-top:120px;
position: absolute;
transition: all 1s ease-in-out;
opacity:0;
color:white;
text-align:center;
}
.circlea{
background-color:rgba( 20, 155, 138 );
}
.circleb{
background-color:rgba( 155, 20, 144 );
}
.circlec{
background-color:rgba( 24, 155, 20);
opacity:1;
}
button{
background-color:tomato;
width:100px;
padding:10px;
color:white;
}
.transforma{
margin-left:200px;
opacity:1;
}
.transformb{
margin-left:800px;
opacity:1;
}
.transformb{
opacity:1;
}
js
$("button").click(function(){
$("div.circleb").toggleClass("transformb");
$("div.circlea").toggleClass("transforma");
});
https://codepen.io/pranjalkoshti/pen/rYNQeL

Categories

Resources