loop jumps from firs if to the second with hammer.js - javascript

I want to use hammer.js pinchout option to switch images (make them larger and fade them).
I've put the images in the background of some divs and I change the css background property to make them larger and disappear. Animating all with webkit.
So far this all works. But I've tried to make a simple switch loop to change the divs one after the other. I first with if and if else and a var to act as switch and later on with the switch option.
The problem is that the the iPad ignores the brakes or pauses and just run the code repentantly from some reason. When I run the code and try to pinchout 2 images change one after the other and the alert given is x-3 (meaning the script did not stop after the first case in the switch and continue to the 3rd before even executing the second!.
please help...
here is the code:
<script type="text/javascript">
var x = 1; // position
var y = 1; // switch
var z = 90; // z-index of layer
var a = 2; // image number (start from image 3 as the first 3 are already set)
window.onload = function() {
Hammer(document.body).on("pinchout", function() {
var box1 = document.getElementById('box1');
var box2 = document.getElementById('box2');
var box3 = document.getElementById('box3');
switch (x)
{
case 1:
box1.style.opacity = "0";
box1.style.backgroundSize = "200% 200%";
x=x+1;
a++;
z--;
break;
case 2:
box2.style.opacity = "0";
box2.style.backgroundSize = "200% 200%";
//box1.style.backgroundImage='url("' + a +'.jpg)"';
box1.style.backgroundSize = "100% 100%";
box1.style.zIndex= z;
x++;
a++;
z--;
alert(x);
break;
case 3:
box1.style.opacity = "1";
box2.style.zIndex= z;
box3.style.opacity = "0"
box3.style.backgroundSize = "200% 200%";
x++;
a++;
z--;
break;
}
});}
</script>

ok,
got it. the pinchout event is not fire only once.
so you need to add something to check when it ends and then run your code.
like this:
var isListening = false;
var instance = Hammer(document.body);
instance.on('pinch', function(e) {
if (isListening) return;
instance.on('release', onPinchEnd);
});
function onPinchEnd(e) {
instance.off('release', onPinchEnd);
alert("here"); // do stuff on pinch end.
}

Related

jQuery nicescroll is not working with dynamic content and other JavaScript function that makes random effect

So here is the thing, I have a sidebar that has big height due the lots of navigation links. And I'm using jQuery nicescroll plugin to make it look fine. In the sidebar I also have h3 tag which makes a random effect of showing letters (see the code) every 4 seconds. So, when it's on - scroll is not working at all for these 4 seconds and you can't do any scrolling. I tried to use $("#sidebar").getNiceScroll().resize() but it doesn't work either. Is there any way to make it work?
<div id="sidebar">
<h3 id="output">Random</h3>
</div>
//Calling for nicescroll function for my sidebar
$(function(){
$("#sidebar").niceScroll({ cursorcolor:"#66aee9", cursorfixedheight: 400 });
})
//Random effect for my h3 tag
setInterval(function(){
$(document).ready(function(){
var theLetters = "abcdefghijklmnopqrstuvwxyz#%&^+=-"; //You can customize what letters it will cycle through
var ctnt = "Random"; // Your text goes here
var speed = 50; // ms per frame
var increment = 8; // frames per step. Must be >2
var clen = ctnt.length;
var si = 0;
var stri = 0;
var block = "";
var fixed = "";
//Call self x times, whole function wrapped in setTimeout
(function rustle (i) {
setTimeout(function () {
if (--i){rustle(i);}
nextFrame(i);
si = si + 1;
}, speed);
})(clen*increment+1);
function nextFrame(pos){
for (var i=0; i<clen-stri; i++) {
//Random number
var num = Math.floor(theLetters.length * Math.random());
//Get random letter
var letter = theLetters.charAt(num);
block = block + letter;
}
if (si == (increment-1)){
stri++;
}
if (si == increment){
// Add a letter;
// every speed*10 ms
fixed = fixed + ctnt.charAt(stri - 1);
si = 0;
}
$("#output").html(fixed + block);
block = "";
}
});
}, 4000);
I change to rows and check it in jsfiddle, looks like working scroll fine.
Before:
setInterval(function(){
$(document).ready(function(){
...
});
}, 4000);
After:
$(document).ready(function(){
setInterval(function(){
...
}, 4000);
});

javascript not working on IE10 / No errors. Works fine on other normal browsers

var depth = 0;
var moving = false;
var answers = new Array();
var qNo = 0;
var rangeCarousel;
var productCarousel;
var ih, iw, orient;
var sidebarOpen = false;
var focused = "range";
var currentRange = 0;
$(document).ready(function () {
document.getElementById('intro').addEventListener('click', clickHandler);
document.getElementById('q1').addEventListener('click', clickHandler);
document.getElementById('q2').addEventListener('click', clickHandler);
document.getElementById('q3').addEventListener('click', clickHandler);
document.getElementById('q4').addEventListener('click', clickHandler);
document.getElementById('intro').addEventListener('webkitTransitionEnd', transitionEnd);
document.getElementById('intro').addEventListener('transitionend', transitionEnd);
document.getElementById('intro').addEventListener('transition', transitionEnd);
});
function clickHandler(e) {
if ((qNo < 4) && (e.target.id != 'intro')) {
qNo++;
if (!moving) {
depth -= 100;
document.getElementById('intro').style.top = (depth + '%');
document.getElementById('q1').style.top = (depth + '%');
document.getElementById('q2').style.top = (depth + '%');
document.getElementById('q3').style.top = (depth + '%');
document.getElementById('q4').style.top = (depth + '%');
moving = true;
}
} else if (qNo == 4) {
var c = e.target.parentNode.classList[0];
switch (c) {
case 'one':
window.open("test.html","_self");
break;
case 'two':
window.open("test.html","_self");
break;
case 'three':
window.open("test.html","_self");
break;
case 'four':
window.open("test.html","_self");
break;
}
}
}
function transitionEnd() {
moving = false;
}
i m trying to create a quiz where users clicks on the images then loads the answer. It works fine on ie11 but i also need to make it work on ie10. I cant see any errors or anything to show me whats wrong
Any help or suggestion will be great
Some old IE does not support target property. You can use e.srcElement which is an alias of target as an alias of target
((e.target || e.srcElement).id) === "intro"
& also use it to find the parentNode
Side Note :As mentioned in comment section you can use jquery as which will also reduce the number of lines in your code beside efficiently handling events
You can also use jquery multiple selector instead of writing same lines of code for attaching event to every selector.
$('sel1 ,selector2 , selector 3 ...').click(function(event){.. rest of code})

Simple JavaScript Game

I want to make a basic Space Invaders clone in ECMAScript/HTML5/CSS3 with the shortest and simplest code possible. I have begun implementing the controls, but they won't work. Here is the code:
<!DOCTYPE html>
<html>
<body onkeydown="javascript:move()" onkeyup=""></body>
<canvas id="myCanvas" width=800 height=800></canvas>
<script>
var context = document.getElementById('myCanvas').getContext("2d");
var img = new Image();
img.onload = function () {
context.drawImage(img, 0, 0, 40, 40);
}
img.src = "run0.png";
function leftArrowPressed() {
img.style.left = parseInt(element.style.left) - 5 + 'px';
}
function rightArrowPressed() {
img.style.left = parseInt(element.style.left) + 5 + 'px';
}
function move(evt) {
var code = window.event.keyCode;
switch (code) {
case 37:
leftArrowPressed();
break;
case 39:
rightArrowPressed();
break;
}
};
</script>
</body>
</html>
You're not handling your keydown event in the markdown of your <body> tag. You can listen to events programatically with JavaScript, or continue as you were doing by adding the move() method to your onkeydown attribute like so:
function leftArrowPressed() {
console.log('move left');
}
function rightArrowPressed() {
console.log('move right');
}
function move(evt) {
var code = window.event.keyCode;
switch (code) {
case 37:
leftArrowPressed();
break;
case 39:
rightArrowPressed();
break;
}
};
<body onkeydown="javascript:move()" onkeyup=""></body>
In order for the above to work (inside an iframe), it must first be focused. So click the white space where the demo opens up before testing.
It should be noted that interfacing the keyboard in browsers has been historically a bit of a headache. Your best bet is to delegate the task to a good library.
I have found the Mousetrap library to be pretty extensive.
You will have a mainloop so just set some flags and attach your key events to the document, no need to worry about focus. Ship will move as long as the key is held down. Fire button will need to have a reload flag and a timer to control the repeat rate. Fire reloads at key up or if reloadTime === 0. When firing set reload to true and reloadTime to repeat rate (in frames). In the key event reload on key up by setting reload = false .
That is about as simple as you can make it.
var framesPerSecond = 30;
var shipX = 0; // ship pos
var leftKeyDown = false; // key down flags
var rightKeyDown = false;
var fireKeyDown = false;
var reloadTime = 0; // fire key needs a timer a timer/counter inbuilt keyboard repeat will take over and mess with your repeat rate.
var reload = false; // dont want the keyboard repeat to trigger shots at the wrong time so
// flag that you need to reload when the next key up
// arrives.
function mainLoop(){
if(leftKeyDown){ // move left if left key down
shipX -= 1;
}
if(rightKeyDown){ // move right if right key down
shipX += 1;
}
if(fireKeyDown && !reload){ //fire is not needing to reload and fire key down
//log("FIRE"); // sends a bullet
reload = true; // need to reload
reloadTime = 10; // number of frames till reload.
}
if(reload && reloadTime > 0){ // if needing to reload
reloadTime -= 1; // count down frames
if(reloadTime === 0){ // until time to reload.
reload = false; // then reload.
}
}
....
// game stuff.
...
// can use requestAnimationFrame if you use canvas
// requestAnimationFrame(mainLoop); // 60 frames a second
// or because you are doing it in HTML
setTimeout(mainLoop,1000 / framesPerSecond);
}
function keyEvent(event){ // handle ky up and downs.
var state = false; // assume up
if(event.type === "keydown"){ // if down
state = true; // set as down
}
if(event.keyCode === 37){ // left key
leftKeyDown = state; // set key state
}else
if(event.keyCode === 39){ // right key
rightKeyDown = state; // set key sate
}else
if(event.keyCode === 32){ // space
fireKeyDown = state;
if(!state && reload){ // reload if needed and key up
reload = false;
}
}
}
document.addEventListener('keydown', keyEvent);
document.addEventListener('keyup', keyEvent);

JS slideshow works one way

My slideshow is suffering from erratic behaviour. it's driven by pagers which the user clicks. when the corresponding pager is clicked, the next image is made visible (opacity/filter) and set as z-index 5 so that it should sit beneath the present image (z-index 10). The current image is then faded-out and finally, the next image is set to current and the image that has faded out is set to z-index 0. However, this only works when clicking back to a previous image (in Chrome, ie is behaving even more strangely.) in the order of images. That is to say,
chrome:
"list_slide1" to "list_slide3" instant jump with no fade
"list_slide3" to "list_slide1" fade behaves correctly
then...
"list_slide1" to "list_slide3" instant jump no fade "list_slide3" to
"list_slide2" fade behaves correctly
or...
"list_slide1" to "list_slide6" instant jump no fade
"list_slide6" to any preceding list-slide1-5 fade behaves correctly
IE:
"list_slide1" to "list_slide3" instant jump with no fade
"list_slide3" to "list_slide1" a second pause then jump
The pagers and the images are dynamically generated from a database (hence the little piece of PHP at the bottom of the code). it contains as many items as are listed for the page in the database.
a few notes:
1) the fade function is my own take on
http://javascript.info/tutorial/animation and has worked just fine in
another slideshow elsewhere on the site.
2) getElementsByClass is from http://www.robertnyman.com and returns
parent and child elements of the requested class in an array (hence
why I call current[0] etc.)
thanks.
<script type="text/javascript">
var pager = document.getElementById('pager1');
var list_pagers = document.getElementById('pagers')
var i = 0;
var next_slide = function(next) {
if (next.className !== 'slide_current') {
if (getElementsByClassName('slide_pending').length === 0) {
var current = getElementsByClassName('slide_current');
next.className = 'slide_pending';
next.style.zIndex = 5;
next.style.opacity = 1;
next.style.filter = 'alpha(opacity = 100)';
next.style.display = 'block';
fade(current[0], linear, 1000);
var fadeSlide = switcher(next, current);
}
}
}
var switcher = function(now, then) {
setTimeout(function() {
now.className = 'slide_current';
now.style.zIndex = 10;
now.style.opacity = 1;
now.style.filter = 'alpha(opacity = 100)';
then[0].className = 'slide_hide';
then[0].style.zIndex = 0;
then[0].style.opacity = 0;
then[0].style.filter = 'alpha(opacity = 0)';
then[0].style.display = 'none';
}, 1001);
}
<?php
// dynamically build event for each pager/slide in the show.
for ($k = 1; $k <= $i; $k++) {
echo 'var next_slide' .$k. ' = document.getElementById("list_slide" +' .$k. '); ',
'addEvent(list_pagers.childNodes[' .($k - 1). '], "click", function () {next_slide(next_slide' .$k. ')}); ';
}
?>
Forgive me for not posting an answer to your exact problem, but I would steer away from writing Javascript plugins yourself for the following reasons:
Hundreds of them exist on the Web already, some of which are developed on GitHub as open source, preventing potential issues through collaborative development.
There is no need to reinvent the wheel; simply spend 20 minutes googling javascript sliders and find one that you can customise to your needs.
A couple I like using are 'caroufredsel', which is responsive and offers a few nice features (dynamically adding items, callbacks etc).
Another is 'flexslider'.
SOLUTION:
the problem was that the <div> tags i was trying to fade each contained an <img> and another <div>... the CSS being applied was either working inconsistently/erratically or - as is IE's wont - not-at-all.... The solution was - rather than animating the fade of the parent <div> - animating the respective child components separately. At first, it looked like the IE solution was completely unto itself; in fact, it was insightful to creating a neat, lightweight non-JQuery slideshow for all the browsers. One trade-off was that I had to incorporate all the styling into the element tags rather than a separate CSS. This seemed like the only viable option in this instance by virtue of the nature of the DOM requests being made...
Questions/feedback gratefully received:
<script type="text/javascript">
var list_pagers = document.getElementById('pagers')
var i = 0;
<?php
// dynamically build event for each pager/slide in the show.
for ($k = 1; $k <= $i; $k++) {
echo 'var next_slide' .$k. ' = document.getElementById("list_slide" +' .$k. '); ',
'addEvent(list_pagers.childNodes[' .($k - 1). '], "click", function () {next_slide(next_slide' .$k. ')}); ';
}
?>
var next_slide = function(next) {
if (next.className !== 'slide_current') {
if (navigator.appName === 'Microsoft Internet Explorer') {
//IE 7 & 8
if ((navigator.appVersion.search('MSIE 8.0') >= 1) || (navigator.appVersion.search('MSIE 7.0') >= 1)) {
var current = getElementsByClassName('slide_current')[0].childNodes[0];
var currentBar = getElementsByClassName('slide_current')[0].childNodes[1];
var nextBar = next.childNodes[1];
var nextSlide = next.childNodes[0];
} else {
//IE 9
var current = getElementsByClassName('slide_current')[0].childNodes[1];
var currentBar = getElementsByClassName('slide_current')[0].childNodes[2];
var nextBar = next.childNodes[2];
var nextSlide = next.childNodes[1];
}
// give the next slide and its header (nextBar) a temporary status of zIndex 5/6
nextSlide.style.zIndex = 5;
nextBar.style.zIndex = 6;
nextSlide.style.filter = "alpha(opacity=100)";
nextBar.style.filter = "alpha(opacity=85)";
fade(currentBar, linear, 500); // fade currentBar out
fade(current, linear, 500); // fade current out
//once we've faded out current slides, it's time to replace them with th
setTimeout(function() {
getElementsByClassName('slide_current')[0].className = 'slide_hide';
next.className = 'slide_current';
nextSlide.style.opacity = 1; // IE 9 includes opacity...
nextBar.style.opacity = 1; // IE 9 includes opacity...
nextSlide.style.filter = "alpha(opacity=100)";
nextBar.style.filter = "alpha(opacity=85)";
nextSlide.style.zIndex = 10;
nextBar.style.zIndex = 11;
}, 500);
} else {
// NON IE TAGS
var current = getElementsByClassName('slide_current')[0];
current.childNodes[1].style.zIndex = 10; // [1] the child <img> tag
current.childNodes[2].style.zIndex = 11; // [2] the child <div> tag
current.childNodes[1].style.opacity = 1;
current.childNodes[2].style.opacity = 0.85;
next.childNodes[1].style.zIndex = 5;
next.childNodes[2].style.zIndex = 6;
next.childNodes[1].style.opacity = 1;
next.childNodes[2].style.opacity = 0.85;
fade(current.childNodes[1], linear, 600); // fade current out
fade(current.childNodes[2], linear, 600); // fade current out
var fadeSlide = setTimeout(function() {switcher(next, current)}, 500);
var switcher = function(now, then, nowBar, thenBar) {
then.className = 'slide_hide';
then.childNodes[1].style.opacity = 0;
then.childNodes[2].style.opacity = 0;
now.className = 'slide_current';
now.childNodes[1].style.opacity = 1;
now.childNodes[2].style.opacity = 0.85;
now.style.opacity = 1;
}
}
}
}
</script>

Change background color with local.Storage (value)

I want to change the background-color of an div:
Arrow Box
For this i have to divs wich you can click. The triggerd function saves the local storage value of the "farbe" key.
<div class="radior" style="background-color:#8066CC;" onClick='localStorage.setItem("farbe","#8066CC");hey()'></div>
So after that, the value of the key "farbe" is asked. Besides this is makes an case ... I think you better read my code, because think i need some englisch lessons sorry!
function hey(){
switch (localStorage.getItem("farbe")){
case "#121212":
var h = "black"
case "#1bc38e":
var h = "turk"
case "#C3594B":
var h = "red"
case "#8066CC":
var h = "lila"
}
document.getElementsByClassName("arrow_box")[0].style.backgroundColor=""+h+""; ;
}
SOmehow it doesnt function!
Or you watch an example of my problem at fiddle http://jsfiddle.net/PpsLH/4/ ! Greetings from Germany!
Change your function to:
hey = function(){
switch (localStorage.getItem("farbe")){
case "#121212":
var h = "black";
break ;
case "#1bc38e":
var h = "turk";
break ;
case "#C3594B":
var h = "red";
break ;
case "#8066CC":
var h = "lila";
break ;
}
document.getElementsByClassName("arrow_box")[0].style.backgroundColor=h;
}
By the way, lila is not a valid HTML color, so it will not work.
You should remove any inline event handlers from your code. Also the whole switch section and changing to named CSS colors seem redundant. Check out this bit of code written in jQuery
var box = $('div.arrow_box');
$('body').on('click','div.radior',function(e){
var color = $(e.target).css('backgroundColor');
localStorage.setItem('farbe',color);
box.css('backgroundColor',color);
});
and a working fiddle http://jsfiddle.net/chrisdanek/BaJvC/5/
try this
<div class="arrow_box"><a>Arrow Box</a></div>
<div class="radior" style="background-color:#C3594B;" onClick="localStorage.setItem('farbe','#C3594B');window.hey()"></div>
<br>
<div class="radior" style="background-color:#8066CC;" onclick='localStorage.setItem("farbe","#8066CC");window.hey()'></div>
and for javascript
window.hey = function ()
{
var h="";
if (localStorage.getItem("farbe")=="#121212")
{
var h = "black";
} else
if (localStorage.getItem("farbe")=="#1bc38e")
{
var h = "turk";
} else
if (localStorage.getItem("farbe")=="#C3594B")
{
var h = "red";
} else
if (localStorage.getItem("farbe")=="#8066CC")
{
var h = "lila";
}
document.getElementsByClassName("arrow_box")[0].style.backgroundColor=h+"";
}

Categories