js code in one html section not working - javascript

when you reduce the browser window there will be a different iphone lay out...
When I put the js into one html sections its not working....
but if i put js in fiddle js section its working properly....
can you tell the reason....
the problem is my li tags are not getting values from js...
can you tell whats the reason....
providing my code below....
working code....
http://jsfiddle.net/YZYp5/7/
not working code....
http://jsfiddle.net/YZYp5/3/
<li style="display: table-cell; width: 417px; vertical-align: top; border: 1px solid red; left: -417px; -webkit-transition: 300ms; -webkit-transform: translate(0px, 0px) translateZ(0px);" data-index="1">
the problem is with this function
function translate(index, dist, speed) {
var slide = slides[index];
var style = slide && slide.style;
if (!style) return;
style.webkitTransitionDuration =
style.MozTransitionDuration =
style.msTransitionDuration =
style.OTransitionDuration =
style.transitionDuration = speed + 'ms';
style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
style.msTransform =
style.MozTransform =
style.OTransform = 'translateX(' + dist + 'px)';
}

The problem seems to be here:
var style = slide && slide.style;
That will make style a boolean value, not an object. You're probably looking for something like this:
var style = slide && slide.style ? slide.style : {};

Related

Javascript won't put array values in CSS syntax

I'm trying to make a slide show using multiple background-images and using the background-position property to animate them. Here is the code:
HTML:
<div class="slide_holder" id="slide_holder"></div>
CSS:
.slide_holder {
float: left;
width: 1440px;
height: 720px;
background-image: url("images/gc-h-s-01.jpg"), url("images/gc-h-s-02.jpg"), url("images/gc-h-s-03.jpg");
background-repeat: no-repeat;
background-size: 100%;
background-position: 0px, 1440px, 2880px;
transition: 1s;
}
JS:
var imageIndex = 1;
var x;
var PosValues = ["0px, 1440px, 2880px", "-1440px, 0px, 1440px", "-2880px, -1440px, 0px"]
startSlides();
function startSlides() {
x = setInterval(IncAndWrite, 1000);
}
function IncAndWrite() {
var i;
document.getElementById("slide_holder").style.backgroundPosition = PosValues[imageIndex];
imageIndex++;
if (imageIndex > 2) {imageIndex = 0;}
}
The concept is that the background-position values for each background-image change every 1s keeping only one image in the visible frame.
The above mentioned code works just fine, but I do not want to write individual position values for different screen sizes (as my website is responsive). So I wrote the following code:
JS:
var imageIndex = 1;
var x;
var UnitRes = 1440;
var PosValues = [
UnitRes*0 + "px, " + UnitRes*1 + "px, " + UnitRes*2 + "px;",
UnitRes*(-1) + "px, " + UnitRes*0 + "px, " + UnitRes*1 + "px;",
UnitRes*(-2) + "px, " + UnitRes*(-1) + "px, " + UnitRes*0 + "px;"]
startSlides();
function startSlides() {
x = setInterval(IncAndWrite, 1000);
}
function IncAndWrite() {
var i;
document.getElementById("slide_holder").style.backgroundPosition = PosValues[imageIndex];
imageIndex++;
if (imageIndex > 2) {imageIndex = 0;}
}
The basic concept is that you put the width of the container in UnitRes and then the values get calculated. But this does not seem to work. The background-position values don't change at all.
What I thought was causing the problem:
In the second case of js code I'm putting a variable value inside an array which I thought is not being converted to a string type while inputing it in the CSS syntax.
What I tried doing:
I used typeof but it is showing the type as string
Then I tried using:
document.getElementById("slide_holder").style.backgroundPosition = PosValues[imageIndex].valueOf();
but still it's not working. I also used alert(PosValues[imageIndex]); to check if the values are ok and they are.
Please help me.
The problem was that in first time you have defined parameters without semicolon ; and in second example you have placed it what broke the script.

adding two .height() 's together? Jquery

I'm trying to add two .height()'s together in order to get a responsive number for my onScroll event how do I add two of these together?
I'm general, I'm just trying to get the animation to fire after getting to the bottom of everything above the element. Is there any other way to do that besides just adding the heights of everything above?
window.addEventListener('load', function() {
$(window).scroll(function() {
var eventScroll = window.pageYOffset;
var eventScrollAmount = ($("#sectionOneImage").height() + $("#bannerOne").height());
if( eventScroll > eventScrollAmount) {
$("#sectionOneImage").addClass("animated slideInLeft ");
}
else {
$("#sectionOneImage").removeClass("animated slideInLeft ");
}
});
});
Here's an example of how to grab two heights using vanilla JS.
var sizeOfOne = document.getElementById('one').offsetHeight;
var sizeOfTwo = document.getElementById('two').offsetHeight;
document.getElementById('hook').innerHTML = 'The first div is ' + sizeOfOne + ' pixels in height, the second div is ' + sizeOfTwo + ' pixels in height. The total size of both div\'s are ' + (sizeOfOne + sizeOfTwo) + ' pixels.';
#one {
height: 50px;
background: red;
}
#two {
height: 75px;
background: blue;
}
<div id="hook"></div>
<div id="one"></div>
<div id="two"></div>

Add a transform value to the current transforms that are already on the element?

Let's say I have a div that had translateX and translateY values added dynamically.
<div class="object child0"
style="-webkit-transform: translateX(873.5px) translateY(256px);
width: 50px; height: 50px;">
I want to add rotateY(20deg) to the current transforms, but applying it via
element.style.webkitTransform = "rotateX(20deg)" loses the other values.
Is there a way to add the rotateY without losing the translateX and translateY transforms?
You could use the += operator to append the rotateX(20deg) to the already existing transformation.
el.style.webkitTransform += "rotateX(20deg)";
Note: I have used a different transformation in the below snippet for the visual effect but method is the same.
window.onload = function() {
var el = document.getElementsByTagName("div")[0];
el.style.webkitTransform += "rotateZ(20deg)";
console.log(el.style.webkitTransform);
document.getElementById("changeDeg").onclick = changeDeg; //event handler
}
function changeDeg() {
var el = document.getElementsByTagName("div")[0];
var re = /(rotateZ)(\(.*(?:deg\)))/g; //regex to match rotateZ(...deg)
var newDeg = 40;
if (el.style.webkitTransform.match(re).length != -1) {
el.style.webkitTransform = el.style.webkitTransform.replace(re, '$1(' + newDeg + 'deg)'); // $1 is first capturing group which is "rotateZ"
}
console.log(el.style.webkitTransform);
}
div {
background: red;
margin-bottom: 20px;
}
<div class="display-object child0" style="-webkit-transform: translateX(43.5px) translateY(6px); width: 50px; height: 50px;"></div>
<button id="changeDeg">Change Rotation</button>
I know this topic is a bit old, and there is a great answer above by Harry.
Though here is an addition in case you need to modify the transform again:
It turns out that that css converts the transform string into a matrix, which makes it extremely hard to understand how to modify (Here is a full documentary).
So string manipulation solutions are the shortest. Here are the good news:
You actually can "stack" multiple transformations!
Try this:
let el = document.getElementsByTagName("div")[0];
// first, sync JS transform with current transform style:
const originalMatrix = window.getComputedStyle(el).transform
if(!el.style.transform){
el.style.transform = originalMatrix
}
// Then apply as much transforms as you whish
let myTransform = " rotate(45deg)"
el.style.transform += myTransform
el.style.transform += myTransform
The div will rotate 90 degrees!
for that to work make sure that the element have some transform declatation beforehand (one can use * {"transform: scale(1)"} in the style sheet)
Now What if you whish to revert all your changes?
const originalMatrix = window.getComputedStyle(el).transform
// Do some changes....
el.style.setProperty('transform', originalMatrix)
Finally, here is a working example:
Click on the div to modify it, or on the body to revert it to original:
window.onload= () => {
let el = document.getElementById("myDiv")
const originalMatrix = window.getComputedStyle(el).transform
document.addEventListener('click', e=>{
if(e.target != el){return revert(el)}
// Sync El transform style
if(!el.style.transform){
el.style.transform = originalMatrix
}
// Aplly some more transforms
el.style.transform = el.style.transform
let myTransform = " translate(20px, 20px) rotate(45deg)"
el.style.transform += myTransform
})
function revert(el){
el.style.setProperty('transform', originalMatrix)
}
}
div{
background:green;
height:50px;
width:100px;
transform:translate(50px, 50px);
transition:1s;
}
<body>
Click body to revert him
<div id="myDiv">ClickMe</div>
</body>

Javascript: Memory efficient way to do this effect

I wrote the code in Javascript but any good alternative would do.
EFFECT: onmousemove over the webpage circles of random colors should create wherever the mouse moves. and they have to be added behind a mask image(circles are visible only in the transparent portion of the image which is a logo. thus creating a color paint to create logo onmousemove.
it doesn't work in jsfidde because of its memory intensiveness.
WORKING LINK: http://goo.gl/DNRxO9
I pasted the exact code you can create a new html file with the following code and IT WORKS PERFECT IN FIREFOX ONLY because of its memory intensiveness(lots of divs added in very short time so DOM becomes very very heavy).
<html>
<head>
<style type="text/css">
body{
padding:0;
margin:0;
overflow: hidden;
}
#mask{
width:100%;
height:auto;
position:absolute;
z-index:10;
}
#logo{
width:50%;
height:50%;
margin:auto;
}
.point{
width:0px;
height:0px;
background-color:#ff0000;
position:absolute;
z-index:5;
left:50px;top:50px;
border-width:50px;
border-style: solid;
border-color:red;
border-radius:50px;
opacity:1;
transition: border-width 3s ease-in-out;
}
.no-border{border-width:0px;}
</style>
<script type="text/javascript">
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
/* OptionalCode: for removing divs after a lot are created */
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
i=0;
function colors(event){
var x=event.clientX;
var y=event.clientY;
var point = document.getElementsByClassName('point');
document.body.innerHTML += "<div class='point'></div>";
point[i].style.borderColor = getRandomColor();
//point[i].className += ' no-border';
point[i].style.left = x + 'px';
point[i].style.top = y + 'px';
i++;
}
function position(){
var ht = window.getComputedStyle(document.getElementById("mask"), null).getPropertyValue("height");
var ht_num = Number(ht.slice(0,ht.length - 2));
margin_top = (Number(document.body.clientHeight) - ht_num)/2;
document.getElementById('mask').style.marginTop = margin_top + "px";
}
</script>
</head>
<body onload="position();" onmousemove="colors(event)">
<img id="mask" src="http://goo.gl/EqfJ0L">
</body>
</html>
There is one HUGE, HUGE, HUGE performance killer in your code:
document.body.innerHTML += "<div class='point'></div>";
This takes your entire document, throws it away and just inserts everything back again. This is horrible! Remember this for all times and never do this again! ;)
Keep the basic rule in mind, to never add Elements via .innerHTML!
The correct way to go is the following:
// create your new div element
var circleElement = document.createElement("div");
// add all the stuff needed
circleElement.classList.add("point");
circleElement.style.borderColor = getRandomColor();
circleElement.style.left = x + 'px';
circleElement.style.top = y + 'px';
// now append the element to the body
document.body.appendChild(circleElement);
This creates a single div and nicely inserts it as a child-element of the body.
Additionally you can decrease the number of divs drawn by introducing a threshhold:
var lastX=0,lastY=0;
function colors(event){
var x=event.clientX;
var y=event.clientY;
if (Math.abs(lastX - x) + Math.abs(lastY - y) <= 10 ) return;
/* do stuff */
lastX = x;lastY = y;
}
As a third measure you can decrease the size of the image to just hold the mask element and trigger the mousemove only on the image (because divs outside the mask are hidden anyway).
Ultimately, you could kill "old" div-elements when you have reached a certain amount.
I have not included these two last optimizations, but look at the already supersmooth example now!

Revealing text on hover image

With my code, i am using a script that generates a random set of 4 images that gets displayed on refresh. I wish to only display the text when the cursor is hovering over the respective image.
Any pointers on doing this with CSS? I am not sure where to put the hover element. http://jsfiddle.net/sugarcraving/Af72K/1/
Javascript
$(document).ready(function() {
$(".champ").hide();
var elements = $(".champ");
var elementCount = elements.size();
var elementsToShow = 4;
var alreadyChoosen = ",";
var i = 0;
while (i < elementsToShow) {
var rand = Math.floor(Math.random() * elementCount);
if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
alreadyChoosen += rand + ",";
elements.eq(rand).show();
++i;
}
}
});
CSS
div.champ {
display: none;
float: left;
color: red;
}
Following what Rouse02 said, add something around the context you want to hide/show.
<p>Celebi, the 251</p>
Then in your css, hide the content and only show it when you hover on the div (you could do it on the image hover as well).
p {
visibility:hidden;
}
.champ:hover p {
visibility:visible;
}
Demo: http://jsfiddle.net/bzTnR/1/
div.champ: hover{
visibility: hidden;
}
div.champ: hover p{
visibility: visible
}
Where p is the element within your div that holds the text.
Hope this helps.
V/R
Maybe this could help! Let me know if this wasn't you were looking for
JsFiddle
I changed CSS to like this : div.text{display:none} div.champ:hover div.text{display:block}
i've updated your fiddle..here..try this
div.champ p{
visibility: hidden;
}
div.champ:hover p{
visibility: visible;
}
updated fiddle

Categories

Resources