Movement Not Being Stopped - javascript

I am trying to prevent a character from crossing objects w/ a blue border. I have included some debugging comments so I can track how the code is being executed, and it seems to be fine logically. However, they way I am trying to prevent movement is not working. And I'm wondering why. Here is my code:
//My HTML Code
<div id="title">
<link rel="stylesheet" type="text/css" href="PM-style.css" media="screen" />
<script src="Pac-Man.js">
</script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="Pac-Man.js">
</script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="Grid.js">
</script>
<title> Pac-Man Game </title>
</div>
<body>
<div class="mazeboard">
<hl> WELCOME!!!</hl>
</div>
<p id="buttons">
<script src="Pac-Man.js">
</script>
<button onclick="myMove()" id="beginButton"> Begin Game </button>
<button onclick="increment()" id="pause"> &nbsp Pause &nbsp </button>
<button onclick="reset()" id="reset"> &nbsp Start Over &nbsp </button>
<button onclick="nextStage1()"> &nbsp Next &nbsp </button>
</p>
<div class='status-window'>
<h2> SCORE: &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp <span> TIME: </span> <span id="output"> </span> </h2>
<script>
</script>
</div>
</div>
<div class="realm">
<canvas width="800" height="450" style="border: 2px solid blue; background-color: black; border-radius: 20px; margin: 0 auto; position: relative; align-content: center;" id="myCanvas"> </canvas>
<!-- Comment This is where the walls go! -->
<div id='game-window'>
<div id="outerwall" class="game-window" data-index="1"> </div>
<div id="left-wall" class="game-window" data-index="2"></div>
<div id="left-wallTop" class="game-window" data-index="3"></div>
<div id="left-wallMiddle" class="game-window" data-index="4"></div>
<div id="left-wallBottom1" class="game-window" data-index="5"></div>
<div id="left-wallBottom2" class="game-window" data-index="6"></div>
<div id="top-wall" class="game-window" data-index="7"></div>
<div id="middle-wall1" class="game-window" data-index="8"></div>
<div id="middle-wall2" class="game-window" data-index="9"></div>
<div id="right-wall" class="game-window" data-index="10"></div>
<div id="center-block" class="game-window" data-index="11"> </div>
<div id="bottom-block1" class="game-window" data-index="12"></div>
<div id="bottom-block2" class="game-window" data-index="13"></div>
<div id="bottom-block3" class="game-window" data-index="14"></div>
<div id="bottom-block4" class="game-window" data-index="15"></div>
<div id="right-bottom1" class="game-window" data-index="16"></div>
<div id="right-bottom2" class="game-window" data-index="17"></div>
<div id="right-bottom" class="game-window" data-index="18"></div>
<div id="center2" class="game-window" data-index="19"></div>
<div id="opencenter" class="game-window" data-index="20"></div>
<div id="center3" class="game-window" data-index="21"></div>
<div id="hole1" class="game-window" data-index="22"></div>
<div id="hole2" class="game-window" data-index="23"></div>
<div id="hole3" class="game-window" data-index="24"></div>
<div id="hole4" class="game-window" data-index="25"></div>
<div></div>
</div>
<script type="text/javascript" src="Pac-man.js"></script>
<script type="text/javascript" src="Ghost.js"></script>
<script type="text/javascript" src="Grid.js"></script>
<script type="text/javascript" src="Game.js"></script>
<script>
window.onload = function() {
var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
}
</script>
<div id='pacman' class='realm'> <img src="https://cdn.pixabay.com/photo/2012/04/14/17/12/pacman-34643_960_720.png" id="pacman"> </div>
<div id='ghost' class='realm'> <img src="https://cdn.pixabay.com/photo/2013/07/12/12/31/pacman-145852_960_720.png" id="ghost"> </div>
</div>
</body>
<footer>
</footer>
</html>
//Moving the Pacman Character (JAVASCRIPT)
$(document).ready(function() {
console.log('jQuery has loaded!');
console.log("Ready!");
$pacman = $(document.getElementById('pacman'));
pacman = $pacman;
STEP_SIZE = 15;
var keys = {};
document.getElementById("beginButton").onclick = function() {
gameStart()
};
function gameStart() {
start();
pacManPositions = {
'left': parseInt(pacman.css('left')),
'right': parseInt(pacman.css('left')) + pacman.width(),
'top': parseInt(pacman.css('top')),
'bottom': parseInt(pacman.css('top')) + pacman.height()
};
//Setting up conditions to determine movement or not
collision2 = false;
collisions = true;
function collision() {
$(".game-window").each(function() {
var walls = document.getElementsByTagName("div");
walls = $(this);
for (var i = 0; i < walls.length; i++) {
var name = walls[i].getAttribute('id');
var border = $(this).css('border-color');
var position = $(this).position();
if (border == 'rgb(0, 0, 255)') {
wallPositions = {
'left': position.left,
'right': position.left + $(this).width(),
'top': position.top,
'bottom': position.top + pacman.height()
};
pacManPositions = {
'left': parseInt(pacman.css('left')),
'right': parseInt(pacman.css('left')) +
pacman.width(),
'top': parseInt(pacman.css('top')),
'bottom': parseInt(pacman.css('top')) +
pacman.height()
};
if ((pacManPositions.left <= wallPositions.left && pacManPositions.right >= wallPositions.left) ||
(pacManPositions.left <= wallPositions.right && pacManPositions.right >= wallPositions.right) ||
(pacManPositions.left <= wallPositions.right && pacManPositions.right >= wallPositions.left)) {
if ((pacManPositions.top >= wallPositions.top && pacManPositions.top <= wallPositions.bottom) ||
(pacManPositions.top <= wallPositions.top && pacManPositions.top >= wallPositions.bottom - 33) ||
(pacManPositions.top >= wallPositions.top && pacManPositions.bottom <= wallPositions.bottom)) {
collisions = false;
return true;
collision2 = true;
}
}
}
}
});
}
//Moving Pac Man w/ Keys
$(document).on('keydown', movePacman);
function movePacman(event) {
console.log(event.which);
switch (event.which) {
//moving right
case 39:
console.log('right');
// pacman.css("left", (pacman.position().left + 10) + "px");
// var leftVal = pacman.css("left", (pacman.position().left + 10) + "px");
var leftVal = parseInt(pacman.css('left')) + STEP_SIZE;
if (leftVal > ($('#outerwall').width() - pacman.width())) {
leftVal = ($('#outerwall').width() - pacman.width()) - 0;
}
collision();
if (collision() == true) {
var leftVal = 0;
$('#pacman').css('left', leftVal);
} else {
$('#pacman').css('left', leftVal);
break;
}
break;
//moving down
case 40:
console.log('down');
var downVal = parseInt(pacman.css('top')) + STEP_SIZE;
if (downVal > ($('#outerwall').height() + pacman.height()) - 70) {
downVal = ($('#outerwall').height()) - pacman.height() + 1;
}
collision();
if (collision() == true) {
} else {
$('#pacman').css('top', downVal);
break;
}
break;
//moving left
case 37:
console.log('left');
var leftVal = parseInt(pacman.css('left')) - STEP_SIZE;
if (leftVal < 0) {
leftVal = ($('#outerwall').width()) - 780;
//parseInt(pacman.css('left'));
}
collision();
if (collision() == true) {
} else {
$('#pacman').css('left', leftVal);
break;
}
// break;
//moving up
case 38:
console.log('up');
var topVal = parseInt(pacman.css('top')) - STEP_SIZE;
if (topVal < 0) {
topVal = ($('#outerwall').height()) - 430;
}
collision();
if (collision() == true) {
} else {
$('#pacman').css('top', topVal);
break;
}
break;
// break;
//breaking
case 32:
console.log('break');
break;
}
}
}
})

Related

zoom in zoom out image on scrolling in javascript

I created tabs with image.When I scroll on the image it will zoom in and zoom out. But I am facing the problem,in only first tab it is working with function zoom in & zoom out(when i scroll).I didn't get what i'm doing wrong.
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>zoom</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<style type="text/css">
ul li{
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Panel title</h3>
<span class="pull-right">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class="active">Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
<li>Tab 4</li>
</ul>
</span>
</div>
<div class="panel-body">
<br />
<br />
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<div class="container">
<div class="slide">
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab2">
<div class="container">
<div class="slide">
<img class='zoom' src='abc.jpg' alt='abc' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab3">
<div class="container">
<div class="slide">
<img class='zoom' src='xy.jpg' alt='xy' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab4">
<div class="container">
<div class="slide">
<img class='zoom' src='rec.png' alt='rec' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- <img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
<br />
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/> -->
<script src="wheelzoom.js"></script>
<script>
wheelzoom(document.querySelector('img.zoom'));
</script>
</body>
</html>
wheelzoom.js
window.wheelzoom = (function(){
var defaults = {
zoom: 0.10,
maxZoom: false,
initialZoom: 1,
};
var main = function(img, options){
if (!img || !img.nodeName || img.nodeName !== 'IMG') { return; }
var settings = {};
var width;
var height;
var bgWidth;
var bgHeight;
var bgPosX;
var bgPosY;
var previousEvent;
var cachedDataUrl;
function setSrcToBackground(img) {
img.style.backgroundRepeat = 'no-repeat';
img.style.backgroundImage = 'url("'+img.src+'")';
cachedDataUrl = 'data:image/svg+xml;base64,'+window.btoa('<svg xmlns="http://www.w3.org/2000/svg" width="'+img.naturalWidth+'" height="'+img.naturalHeight+'"></svg>');
img.src = cachedDataUrl;
}
function updateBgStyle() {
if (bgPosX > 0) {
bgPosX = 0;
} else if (bgPosX < width - bgWidth) {
bgPosX = width - bgWidth;
}
if (bgPosY > 0) {
bgPosY = 0;
} else if (bgPosY < height - bgHeight) {
bgPosY = height - bgHeight;
}
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
}
function reset() {
bgWidth = width;
bgHeight = height;
bgPosX = bgPosY = 0;
updateBgStyle();
}
function onwheel(e) {
var deltaY = 0;
e.preventDefault();
if (e.deltaY) { // FireFox 17+ (IE9+, Chrome 31+?)
deltaY = e.deltaY;
} else if (e.wheelDelta) {
deltaY = -e.wheelDelta;
}
// As far as I know, there is no good cross-browser way to get the cursor position relative to the event target.
// We have to calculate the target element's position relative to the document, and subtrack that from the
// cursor's position relative to the document.
var rect = img.getBoundingClientRect();
var offsetX = e.pageX - rect.left - window.pageXOffset;
var offsetY = e.pageY - rect.top - window.pageYOffset;
// Record the offset between the bg edge and cursor:
var bgCursorX = offsetX - bgPosX;
var bgCursorY = offsetY - bgPosY;
// Use the previous offset to get the percent offset between the bg edge and cursor:
var bgRatioX = bgCursorX/bgWidth;
var bgRatioY = bgCursorY/bgHeight;
// Update the bg size:
if (deltaY < 0) {
bgWidth += bgWidth*settings.zoom;
bgHeight += bgHeight*settings.zoom;
} else {
bgWidth -= bgWidth*settings.zoom;
bgHeight -= bgHeight*settings.zoom;
}
if (settings.maxZoom) {
bgWidth = Math.min(width*settings.maxZoom, bgWidth);
bgHeight = Math.min(height*settings.maxZoom, bgHeight);
}
// Take the percent offset and apply it to the new size:
bgPosX = offsetX - (bgWidth * bgRatioX);
bgPosY = offsetY - (bgHeight * bgRatioY);
// Prevent zooming out beyond the starting size
if (bgWidth <= width || bgHeight <= height) {
reset();
} else {
updateBgStyle();
}
}
function drag(e) {
e.preventDefault();
bgPosX += (e.pageX - previousEvent.pageX);
bgPosY += (e.pageY - previousEvent.pageY);
previousEvent = e;
updateBgStyle();
}
function removeDrag() {
document.removeEventListener('mouseup', removeDrag);
document.removeEventListener('mousemove', drag);
}
// Make the background draggable
function draggable(e) {
e.preventDefault();
previousEvent = e;
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', removeDrag);
}
function load() {
var initial = Math.max(settings.initialZoom, 1);
if (img.src === cachedDataUrl) return;
var computedStyle = window.getComputedStyle(img, null);
width = parseInt(computedStyle.width, 10);
height = parseInt(computedStyle.height, 10);
bgWidth = width * initial;
bgHeight = height * initial;
bgPosX = -(bgWidth - width)/2;
bgPosY = -(bgHeight - height)/2;;
setSrcToBackground(img);
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
img.addEventListener('wheelzoom.reset', reset);
img.addEventListener('wheel', onwheel);
img.addEventListener('mousedown', draggable);
}
var destroy = function (originalProperties) {
img.removeEventListener('wheelzoom.destroy', destroy);
img.removeEventListener('wheelzoom.reset', reset);
img.removeEventListener('load', load);
img.removeEventListener('mouseup', removeDrag);
img.removeEventListener('mousemove', drag);
img.removeEventListener('mousedown', draggable);
img.removeEventListener('wheel', onwheel);
img.style.backgroundImage = originalProperties.backgroundImage;
img.style.backgroundRepeat = originalProperties.backgroundRepeat;
img.src = originalProperties.src;
}.bind(null, {
backgroundImage: img.style.backgroundImage,
backgroundRepeat: img.style.backgroundRepeat,
src: img.src
});
img.addEventListener('wheelzoom.destroy', destroy);
options = options || {};
Object.keys(defaults).forEach(function(key){
settings[key] = options[key] !== undefined ? options[key] : defaults[key];
});
if (img.complete) {
load();
}
img.addEventListener('load', load);
};
// Do nothing in IE9 or below
if (typeof window.btoa !== 'function') {
return function(elements) {
return elements;
};
} else {
return function(elements, options) {
if (elements && elements.length) {
Array.prototype.forEach.call(elements, main, options);
} else if (elements && elements.nodeName) {
main(elements, options);
}
return elements;
};
}
}());
When i scroll it is zoom in and zoom out but only in first tab.What I did wrong,i can't understand.Please help me.Thank you.
Nice work i worked it out and find that you are using wheelzoom(document.querySelector('img.zoom')); here in this code you are using querySelector where this code will return only one element not all element instead of this code you need to use wheelzoom(document.querySelectorAll('img.zoom')); then your example will work . I have tried and its working

Bootstrap modal darkens screen but won't show

I'm trying to get a modal to display upon my page loading. The problem is, the screen darkens, but the modal itself does not display.
As per the site's suggestion, here is an abbreviated version of my code. Here is the head:
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#ball {
position: absolute;
left: 208px;
top: 40px;
z-index: 1;
width: 20px;
height: 20px;
transition: top 1s;
}
#wheel {
}
#da_panel
{
position: relative;
z-index:1;
}
.row {
padding: 20px;
}
</style>
</head>
Here is where the modal loads
<body onload = "populate(); loadModal();">
<div class="modal hide fade" id="myModal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
Close
Save changes
</div>
</div>
And here is the function:
<script>
function loadModal(){
$('#myModal').modal('show');
}
Also, if you just want to look at the whole shabang, here it is:
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#ball {
position: absolute;
left: 208px;
top: 40px;
z-index: 1;
width: 20px;
height: 20px;
transition: top 1s;
}
#wheel {
}
#da_panel
{
position: relative;
z-index:1;
}
.row {
padding: 20px;
}
</style>
</head>
<body onload = "populate(); loadModal();">
<div class="modal hide fade" id="myModal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
Close
Save changes
</div>
</div>
<div class = "container">
<div class = "row">
<div class = "col-lg-5">
<img id = "ball" src = "ball.png" onclick="spin()"></img>
<img id = "wheel" src = "Rwheelbg.png" onclick="spin()"></img>
</div>
<div class = "col-lg-1">
<button id = "reset" onclick="reset()">Reset Wheel</button>
</div>
<div class = "col-lg-6">
<div class="well well-lg">
<span><center>Chips</center></span>
<br>
<div class = "text-center" style = "font-size: 180px;" id = "chipsInv">10</div>
<!-- Why won't this center!? -->
<br>
<span style = "float:left" id = "earnings">Your earnings:</span>
<span style = "float:right;" id ="purchase" onclick="purchase()"><a style = "color:green !important;" href = "#">$ Purchase More Chips?</a></span>
<!-- Must find way to override link color -->
</div>
</div>
<!-- Row ends here -->
<!-- FIND A WAY TO MAKE IMAGE TRANSPARENT!!! -->
</div>
<div class="panel panel-default" id = "da_panel">
<div class="panel-heading">Bet on:</div>
<div class="panel-body">
<form action="">
<input type="checkbox" name="21" value="310" id = "310"> 21<br>
<input type="checkbox" name="9" value="100" id = "100"> 9<br>
<input type="checkbox" name="14" value="120" id = "120"> 14<br>
<input type="checkbox" name="13" value="240" id = "240"> 13
</form>
</div>
</div>
<!-- <p>Bet on:</p>
<form action="">
<input type="checkbox" name="21" value="310" id = "310"> 21<br>
<input type="checkbox" name="9" value="100" id = "100"> 9<br>
<input type="checkbox" name="14" value="120" id = "120"> 14<br>
<input type="checkbox" name="13" value="240" id = "240"> 13
</form> -->
<p>Bet on up to four numbers. However, be warned, the more numbers you bet on, the lower your chip return will be.</p>
<!-- container ends here -->
</div>
<script>
function loadModal(){
$('#myModal').modal('show');
}
var chips = 5;
var earnings = chips * (-1);
function populate()
{
$("#chipsInv").text(chips);
$("#earnings").text("Your earnings: " + earnings)
}
function purchase()
{
chips = chips + 1;
$("#chipsInv").text(chips);
earnings = earnings - 1;
$("#earnings").text("Your earnings: " + earnings);
}
function gainChips(number)
{
chips = chips + number;
$("#chipsInv").text(chips);
earnings = earnings + number;
$("#earnings").text("Your earnings: " + earnings);
}
function loseChip()
{
chips--;
$("#chipsInv").text(chips);
if (chips == 0)
{
alert("You are out of chips. Purchase more chips to continue betting.")
}
}
// 21 = 310
// 23 = 190 degrees
// 9 = 100
// 14 = 120 degrees
// 13 = 240
var randomNum = Math.floor(Math.random() * 355) + 1;
var rw=document.getElementById('wheel');
var rb = document.getElementById('ball');
function rotate(degrees){
rw.setAttribute('style', 'transition: transform 1s; transform:rotate(' + 360 + degrees + 'deg)');
console.log(degrees);
}
function spin(){
for (i = 0; i < randomNum; i = i + 10) {
console.log("2");
rotate(i);
}
var winningDegrees = i - 10;
console.log(winningDegrees);
function winLoss()
{
//some kind of array to run through.
var possBets = [310, 100, 120, 240];
var checkedBets = [];
var divisor = 0;
var winner = false;
for (i = 0; i < possBets.length; i++) {
//check which boxes were checks, and pushes them to a
//checked array
if (document.getElementById(possBets[i]).checked == true)
{
checkedBets.push(possBets[i]);
}
}
divisor = checkedBets.length;
//now you have to ask do any of the checkBets == winningDegrees
//checks if any of the checked bets were winning bets
for (i = 0; i < checkedBets.length; i++) {
if (checkedBets[i] == winningDegrees)
{
winner = true;
}
}
if (winner == true)
{
var earnings = 36/divisor;
alert("Yay! U r teh winz! You earned " + earnings + " chips.");
gainChips(earnings);
}
else if (divisor > 0)
{
alert("You lost 1 chip.")
loseChip();
}
//function winLoss ends here
}
function ballDrop() {
setTimeout(function(){ rb.style.top = "90px";}, 1050);
if (chips > 0)
{
setTimeout(winLoss, 2000);
}
}
ballDrop();
//end of spin function()
}
function reset(){
rw.setAttribute('style', 'transform:rotate(0deg)');
rb.style.top = "50px";
randomNum = Math.floor(Math.random() * 355) + 1;
}
</script>
</body>
</html>
That is because of the hide class you gave to #myModal.
Here is what is seen in the code inspector:
.hide{
display: none!important;
}
So you can remove that class from this markup: <div class="modal hide fade" id="myModal">
Or use .removeClass() like this: $('#myModal').removeClass("hide").modal('show');

How to moves the divs by clicking on each one

I want to when I click on every div
It's the first to be in front of everyone and the others div are moved.for example div4 is in front of everyone.when I click on div1 I want to put div1 in place of div4 and Then again, on each one that I click on, it's the front but My code does not work properly after several times and does not display one of the shapes.
$(".haml-category").click(function() {
var top = $(this).data("top");
var zindex = $(this).data("zindex");
var temp = $(".haml-category-container").find(".selected");
$(".haml-category-container").find(".selected").removeClass("selected").data("zindex", zindex).data("top", top).css({
"z-index": zindex,
"top": top
});
$(this).data("zindex", temp.data("zindex")).data("top", temp.data("top")).addClass("selected");
});
.haml-category-container {
position: relative;
background-color:#ccc;
}
.haml-category {
position: absolute;
width: 100%;
height: 500px;
top: 0;
right: 0;
border: 1px solid black;
transition: top 1s;
}
.sec-saheb-bar {
z-index: 0;
}
.sec-ranande {
z-index: 1;
top: 40px;
}
.sec-barbar {
z-index: 2;
top: 85px;
}
.sec-bazaryab {
z-index: 3;
top: 130px;
}
.selected {
z-index: 3;
top: 130px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="haml-category-container">
<div class="haml-category sec-saheb-bar" id="sec-saheb-bar" data-zindex="0" data-top="0">
<h6>div1</h6>
<p> content div1</p>
</div>
<div class="haml-category sec-ranande" id="sec-ranande" data-zindex="1" data-top="40">
<h6>div2</h6>
<p> content div2</p>
</div>
<div class="haml-category sec-barbar" id="sec-barbar" data-zindex="2" data-top="85">
<h6>div3</h6>
<p> content div3</p>
</div>
<div class="haml-category sec-bazaryab selected" id="sec-bazaryab" data-zindex="3" data-top="130">
<h6>div4</h6>
<p> content div4</p>
</div>
</div>
The variable temp may has be changed,modified as below.
$(".haml-category").click(function() {
var top = $(this).data("top");
var zindex = $(this).data("zindex");
var temp = $(".haml-category-container").find(".selected");
var top2 = temp.data("top");
var zindex2 = temp.data("zindex");
$(this).data("zindex", zindex2).data("top", top2).css({
"z-index": zindex2,
"top": top2
}).addClass("selected");
temp.removeClass("selected").data("zindex", zindex).data("top", top);
temp.css({
"z-index": zindex,
"top": top
});
});
.haml-category-container {
position: relative;
}
.haml-category {
position: absolute;
width: 100%;
height: 500px;
top: 0;
right: 0;
border: 1px solid black;
transition: top 1s;
}
.sec-saheb-bar {
z-index: 0;
}
.sec-ranande {
z-index: 1;
top: 40px;
}
.sec-barbar {
z-index: 2;
top: 85px;
}
.sec-bazaryab {
z-index: 3;
top: 130px;
}
.selected {
z-index: 3;
top: 130px;
}
#sec-saheb-bar{
background-color:#0077CC;
}
#sec-ranande{
background-color:#1F1D1C;
}
#sec-barbar{
background-color:#FECD45;
}
#sec-bazaryab{
background-color:#1AA160;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="haml-category-container">
<div class="haml-category sec-saheb-bar" id="sec-saheb-bar" data-zindex="0" data-top="0">
<h6>div1</h6>
</div>
<div class="haml-category sec-ranande" id="sec-ranande" data-zindex="1" data-top="40">
<h6>div2</h6>
</div>
<div class="haml-category sec-barbar" id="sec-barbar" data-zindex="2" data-top="85">
<h6>div3</h6>
</div>
<div class="haml-category sec-bazaryab selected" id="sec-bazaryab" data-zindex="3" data-top="130">
<h6>div4</h6>
</div>
</div>
I did this FRANKENSTEIN's monster in 2010 for testing purpose.how you can see i put everywhere z-index:9 watch the demo try to drag every element over other element.with some modifications you can convert it in jquery
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
<HEAD>
<TITLE></TITLE>
<style></style>
<meta charset="UTF-8">
<SCRIPT LANGUAGE="JavaScript">
<!--
// function returns array of box bounds
box_offset = function (box) {
var scrollPosition = getScrollPosition(), // get scroll position
oLeft = 0,// - scrollPosition[0], // define offset left (take care of horizontal scroll position)
oTop = 0,// - scrollPosition[1], // define offset top (take care od vertical scroll position)
box_old = box; // remember box object
// loop to the root element and return box offset (top, right, bottom, left)
do {
oLeft += box.offsetLeft;
oTop += box.offsetTop;
box = box.offsetParent;
}
while (box);
// return box offset array
// top right, bottom left
//return [ oTop, oLeft + box_old.offsetWidth, oTop + box_old.offsetHeight, oLeft ];
// top right, bottom left
return [
oLeft,
oLeft + box_old.offsetWidth,
oTop,
oTop + box_old.offsetHeight
];
};
// function returns scroll positions in array
getScrollPosition = function () {
// define local scroll position variables
var scrollX, scrollY;
// Netscape compliant
if (typeof(window.pageYOffset) === 'number') {
scrollX = window.pageXOffset;
scrollY = window.pageYOffset;
}
// DOM compliant
else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
scrollX = document.body.scrollLeft;
scrollY = document.body.scrollTop;
}
// IE6 standards compliant mode
else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
scrollX = document.documentElement.scrollLeft;
scrollY = document.documentElement.scrollTop;
}
// needed for IE6 (when vertical scroll bar was on the top)
else {
scrollX = scrollY = 0;
}
// return scroll positions
return [ scrollX, scrollY ];
};
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
swdrag = false;
var picwidth;
var picheight;
var picxpos;
var picypos;
var Drag = {
obj : null,
init : function(o, resizer, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
{
o.onmousedown = Drag.start;
o.resizer = resizer;
o.root = o;
if ( isNaN(parseInt(o.root.style.left ))) o.root.style.left = "0px";
if ( isNaN(parseInt(o.root.style.top ))) o.root.style.top = "0px";
o.root.onDragStart = new Function();
o.root.onDragEnd = new Function();
o.root.onDrag = new Function();
calculate();
},
start : function(e)
{
var o = Drag.obj = this;
e = Drag.fixE(e);
var y = parseInt( o.root.style.top );
var x = parseInt( o.root.style.left );
o.root.onDragStart(x, y);
o.lastMouseX = e.clientX;
o.lastMouseY = e.clientY;
document.onmousemove = Drag.drag;
document.onmouseup = Drag.end;
calculate();
return false;
},
drag : function(e)
{
e = Drag.fixE(e);
var o = Drag.obj;
var nx, ny;
var ey = e.clientY;
var ex = e.clientX;
var changeX = (ex - o.lastMouseX);
var changeY = (ey - o.lastMouseY);
nx = parseInt(o.root.style.left ) + changeX;
ny = parseInt(o.root.style.top ) + changeY;
if (o.xMapper) nx = o.xMapper(y)
else if (o.yMapper) ny = o.yMapper(x)
Drag.obj.root.style["left"] = nx + "px";
Drag.obj.root.style["top"] = ny + "px";
Drag.obj.lastMouseX = ex;
Drag.obj.lastMouseY = ey;
Drag.obj.root.onDrag(nx, ny);
Drag.xmouse = Drag.obj.lastMouseX;
Drag.ymouse = Drag.obj.lastMouseY;
Drag.xmouse = e.clientX;
Drag.ymouse = e.clientY;
calculate();
calculate2();
swdrag=true;
return false;
},
end : function()
{
document.onmousemove = null;
document.onmouseup = null;
Drag.obj.root.onDragEnd( parseInt(Drag.obj.root.style["right"]),
parseInt(Drag.obj.root.style["bottom"]));
Drag.obj = null;
calculate();
if (swdrag){
swdrag = false;
}
},
fixE : function(e)
{
if (typeof e == 'undefined') e = window.event;
if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
Drag.xmouse=e.clientX;
Drag.ymouse=e.clientY;
calculate();
return e;
},
xmouse:0,
ymouse:0
};
function start(){
IMAGE.style.left=x_pic_ini;
IMAGE.style.top=y_pic_ini;
//calculate();
}
function calculate(){
widthIMAGE=parseInt(IMAGE.clientWidth);
picwidth=widthIMAGE;
heightIMAGE=parseInt(IMAGE.clientHeight);
picheight=heightIMAGE;
xposex=parseInt(IMAGE.style.left);
yposex=parseInt(IMAGE.style.top);
picxpos=xposex;
picypos=yposex;
IMAGE.left=picxpos;
IMAGE.top=picypos;
}
function calculate2(){
oobj=document.f1;
oobj.xpic.value=picxpos;
oobj.ypic.value=picypos;
//fiecare celula | every box
if(lastbox!=null)
{
//lastbox.style.background='white';
//lastbox.style.color='black';
}
mxrows=document.getElementById("tb1").rows.length;
for(i=0;i<mxrows;i++){
mxcols=document.getElementById("tb1").rows[i].cells.length;
for(u=0;u<3;u++){
//a("i"+i+u+"=");
theboxobj=eval(document.getElementById("i"+i+u));
xyb=box_offset(theboxobj);
oox=picxpos;
ooy=picypos+(heightIMAGE-theboxobj.clientHeight)/2;
if ((oox>xyb[0])&&(oox<xyb[1])&&(ooy>xyb[2])&&(ooy<xyb[3]))
{
a('i('+i+' '+u+')');
theboxobj.style.background='red';
theboxobj.style.color='yellow';
lastbox=theboxobj;
if(!swdrag){
break;
// imobj=document.getElementById("image");
//document.write(obj2(obj,'obj'));
// oldobj=imobj.outerHTML;
// imobj=new Object();
// lastbox.appendChild(imobj);
lastbox.parentNode.removeChild(lastbox);
//imobj=new Object();
lastbox.parentNode.appendChild(imobj);
lastbox.parentNode.outerHTML='<td>xx</td>';
// imobj.parentNode.removeChild(imobj);
// lastbox.innerHTML=oldobj;
}
//alert(oldobj);
break;
}
}
}
}
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
//---------------obj 2 --------------------------------
function obj2(obj, obj_name) {
var result = "";
for (var i in obj)
result += obj_name + "." + i + " = " + obj[i] +'-'+typeof obj[i]+ "\n<br>\n";
return result
}
function obj1(obj,txt){//obj(this.style)
tt=document.open('about:blank','here','');
tt.document.write(obj2(obj,txt));
}
//-----------------------------------------------------
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
ids=new Array();
ids[0]='dsdsad';
ids[1]='tre1';
ids[2]='image';
ids[3]='image2';
ids[4]='newd';
ids[5]='txt';
function overb(obj){
color='#FF0000';
width='3px';
obj.style.borderTopWidth = width;
obj.style.borderTopColor =color;
obj.style.borderTopStyle ='solid';
obj.style.borderLeftWidth = width;
obj.style.borderLeftColor =color;
obj.style.borderLeftStyle ='solid';
obj.style.borderRightWidth = width;
obj.style.borderRightColor =color;
obj.style.borderRightStyle ='solid';
obj.style.borderBottomWidth = width;
obj.style.borderBottomColor =color;
obj.style.borderBottomStyle ='solid';
obj.style.zIndex='999';
off=box_offset(obj);
x_pic_ini=off[0];
y_pic_ini=off[2];
IMAGE=document.getElementById(obj.id);
//obj1(IMAGE,'IMAGE');
Drag.init(IMAGE);
start();
}
function outb(obj){
obj.style.borderTopWidth = '0px';
obj.style.borderLeftWidth = '0px';
obj.style.borderRightWidth = '0px';
obj.style.borderBottomWidth = '0px';
obj.style.zIndex='9'
}
//-->
</SCRIPT>
</HEAD>
<BODY onload="">
<FORM METHOD=POST ACTION="#" NAME="f1">
<div style="position:absolute;left:50;top:50;z-index:9;"
onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="canalica">xpic<INPUT TYPE="text" NAME="xpic"></div>
<div style="position:absolute;left:50;top:75;z-index:9;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="tre1">ypic<INPUT TYPE="text" NAME="ypic"></div>
<div style="position:absolute;left:50;top:75;z-index:9;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="submit">ypic<INPUT TYPE="submit" NAME="submit" value="submit"></div>
</FORM><HR>
<div style="position:absolute;left:50;top:150;z-index:9;border-top:1px solid green;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="image">Yes!</div>
<div style="position:absolute;left:50;top:150;z-index:9;border-top:1px solid green;" onmouseover="overb(this);doit(this);" onmouseout="outb(this);" id="image2">yep yep !</div>
<div style="position:absolute;left:50;top:150;z-index:9;border-top:1px solid green;" onmouseover="overb(this);/*document.write(obj2(this.style,'this.style'));*/doit(this)" onmouseout="outb(this);" id="newd"><TABLE border="1px" CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="500" id="tb1" align="left" style="margin:0;">
<TR>
<TD id="i00">11</TD>
<TD id="i01">12</TD>
<TD id="i02">13</TD>
</TR>
<TR>
<TD id="i10">21</TD>
<TD id="i11">22</TD>
<TD id="i12">23</TD>
</TR>
<TR>
<TD id="i20">31</TD>
<TD id="i21">32</TD>
<TD id="i22">33</TD>
</TR>
</TABLE></div>
<FORM METHOD=POST ACTION="#" NAME="f3">
<TEXTAREA style="position:absolute;left:50;top:175;z-index:9;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="txt" NAME="aa" ROWS="20" COLS="20"></TEXTAREA>
</FORM>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<script type="text/javascript">
//-----------------------------------------------------
var x_pic_ini, y_pic_ini,IMAGE;
function doit(obj){
}
//------------------------------------------------------
</script>
<SCRIPT LANGUAGE="JavaScript">
<!--
/* for(i=0;i<ids.length;i++){
oo=document.getElementById(ids[i]);
//obj1(oo,'oo');
oo.style.Left=i*20;
oo.style.Top=i*20;
//alert(ids[i]);
}*/
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
function a(val){
ww=document.f3.aa.value+val;
document.f3.aa.value=ww;
}
var div1=document.getElementById("newd");
div1.style.left=600;
div1.style.top=200;
//fiecare celula
for(i=0;i<3;i++){
for(u=0;u<3;u++){
a("i"+i+u+"=");
a(box_offset(eval(document.getElementById("i"+i+u)))+'\n');
}
}
var lastbox=null;
//doar div-ul..
//alert(box_offset(div1));
//-->
</SCRIPT>
</BODY></HTML>

How to set total height on Jinvert Scroll

I've created a horizontal scrolling website with parallax using Jquery Plugin called Jinvertscroll. However, the scrolling stops before reaching the end of the page. Demo at https://dl.dropboxusercontent.com/u/246684898/VipSitaraman.com/examples/index.htm. Please tell me how to change the total scroll length on the plug in.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Vip Sitaraman</title>
<link rel="stylesheet" href="css/example.css" />
<body style="background-color:#383938">
<div id="main">
<div class="suit scroll">
<img id="animation" src="images/1.png" alt="" />
</div>
<div class="plane scroll">
<img class="plane" src="images/plane.png" alt="" />
</div>
<div class="pinned scroll">
<a id="navv">< </a><a id="nav"> ></a>
</div>
<div class="bg scroll">
<img src="images/bg.jpg" alt="" />
</div>
<div class="horizon scroll">
<img src="images/horizon_01.png" alt="" />
</div>
<div class="middle scroll">
<img src="images/middle_01.png" alt="" />
</div>
<div class="front scroll">
<img src="images/front_01.png" alt="" />
</div>
<div class="research scroll" id="research">
</div>
<div class="music scroll" id="music">
</div>
</div>
</div>
</div>
<script type="text/javascript" src="../libs/jquery.min.js"></script>
<script type="text/javascript" src="../dist/js/jquery.jInvertScroll.js"></script>
<script type="text/javascript">
(function($) {
$.jInvertScroll(['.scroll'], // an array containing the selector(s) for the elements you want to animate
{
height: 3000, // optional: define the height the user can scroll, otherwise the overall length will be taken as scrollable height
onScroll: function(percent) { //optional: callback function that will be called when the user scrolls down, useful for animating other things on the page
console.log(percent);
}
});
}(jQuery));
</script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
var b = 300
var bodyHeight = $("body").height()-$(window).height();
window.onscroll = function() {
if($('#animation').attr('src') != 'images/suit.gif'){
$('#animation').attr('src','images/suit.gif');
};
};
});//]]>
</script>
<script type='text/javascript'>//<![CDATA[
$(function (){
var sdegree = 0;
var orig = 0;
var z = 1 + Math.random() * 20
$(window).scroll(function () {
if (sdegree > -10 && sdegree < 10 && sdegree - orig >= 0) {
orig = sdegree;
sdegree = sdegree + 1;
} else if (sdegree > -10 && sdegree < 10 && sdegree - orig < 0) {
orig = sdegree;
sdegree = sdegree - 1;
} else if (sdegree <= -10) {
orig = sdegree;
sdegree = sdegree + 1;
} else if (sdegree >= 10) {
orig = sdegree;
sdegree = sdegree - 1;
} else {
orig = sdegree;
}
var srotate = "rotate(" + sdegree + "deg)";
$('.plane').css('z-index','z');
$(".plane").css({
transform: srotate
});
});
});
//]]>
</script>
<script type="text/javascript">
$(function() {
$("#nav").click(function() {
$('html,body').animate({
scrollTop: $(document).scrollTop()+800
}, 1000);
if($('#animation').attr('src') != 'images/suit.gif'){
$('#animation').attr('src','images/suit.gif');
}
});
});
</script>
<script type="text/javascript">
$(function() {
$("#navv").click(function() {
$('html,body').animate({
scrollTop: $(document).scrollTop()-800
}, 1000);
});
});
</script>
</body>
</html>
If all you need is to define size, here's what you are looking for:
$.jInvertScroll(['.myScrollableElements'], {
width: 'auto', // Page width (auto or int value)
height: 'auto', // Page height (the shorter, the faster the scroll)
onScroll: function(percent) {
// Callback function that will be called each time the user
// scrolls up or down, useful for animating other parts
// on the page depending on how far the user has scrolled down
// values go from 0.0 to 1.0 (with 4 decimals precision)
}
});
SOURCE

Selecting proper elements of a div by navigation keys

I have a list of images displayed on my page with multiple divs laid on top of each other.
The divs are displayed according to the button clicked.
I want to select the images using the navigation keys.
Can someone point me a direction.
Code so far - Fiddle Demo
Here the image with property 'selected' is shown with blue color. On click of arrowkeys, I want respective image should be highlighted.
<div>
<div id="page1" class="button">SHOW PAGE1</div>
<div id="page2" class="button">SHOW PAGE2</div>
</div>
<div id="a1" class="container"> Page 1
<img class="item" />
<img class="item" />
<img class="item" />
<img class="item" />
<img class="item" />
</div>
<div id="a2" class="container" hidden> Page 2
<img class="item" />
<img class="item" />
<img class="item" />
<img class="item" />
<img class="item" />
<img class="item" />
<img class="item" />
</div>
You can use trigger() function for that
$(document).keydown(function(e) {
switch(e.which) {
case 37: // left
$('#page1').trigger('click');
break;
case 38: // up
$('#page2').trigger('click');
break;
case 39: // right
$('#page2').trigger('click');
break;
case 40: // down
$('#page1').trigger('click');
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
demo
This solution has integrated page switching in it.
var $rows = $('.myrow'),
$cells = $('.mycell');
$(document).keydown(function (e) {
var arrowKeys = [37, 38, 39, 40];
var directions = ['left', 'up', 'right', 'down'];
var arrowIndex = $.inArray(e.which, arrowKeys);
if (arrowIndex !== -1) {
var dir = directions[arrowIndex];
var $currCell = $cells.filter('.selected').removeClass('selected');
var cellIndex = $currCell.index();
var $currRow = $currCell.parent();
if (dir == 'up' || dir == 'down') {
switchRows($currRow, dir, cellIndex);
} else {
var $nextCell;
if( dir=='left'){
$nextCell= $currCell.prev().addClass('selected');
if( !$nextCell.length){
switchRows($currRow, 'up', 150000);
}
}else{
$nextCell= $currCell.next().addClass('selected');
if( !$nextCell.length){
switchRows($currRow, 'down',0);
}
}
}
e.preventDefault(); // prevent the default action (scroll / move caret)
}
});
/* switches rows and toggles page visibility if next image on another page going up or down*/
function switchRows ($currRow, direction, cellIndex) {
var $next, curRowIndex = $rows.index( $currRow);
if (direction == 'up') {
$next = $rows.eq(curRowIndex-1)
$next = $next.length ? $next : $rows.last();
} else {
$next = $rows.eq(curRowIndex+1)
$next = $next.length ? $next : $rows.first();
}
var $nextCell= $next.find('.mycell').eq(cellIndex);
if( !$nextCell.length){
$nextCell= $next.find('.mycell').last();
}
$nextCell.addClass('selected');
$currRow.parent().hide();
$next.parent().show();
/* add button class change logic */
}
DEMO
check this fiddle. keypress is not working in fiddle.
Just copy the entire script from that fiddle and paste in your page and test in browser.
It will work. http://jsfiddle.net/abhiklpm/m3MK3/12/
$(document).ready(function () {
var listItems = $(".item");
listItems.each(function (index, value) {
if (index % 4 == 0) {
$(this).addClass('clear')
// what should i do here?
}
});
$(document).keypress(function(e) {
switch(e.keyCode) {
case 37: // left
moveLeft();
break;
case 38: // up
moveUp();
break;
case 39: // right
moveRight();
break;
case 40: // down
moveDown();
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
$('.item').on('click',function(){
$('.item').removeClass('selected');
$(this).addClass('selected');
});
$('#page1').on('click', function(){
$("#a2").hide();
$('#a1').show();
$('#a1 .myrow:first-child .item:first-child').addClass('selected').trigger('click');
});
$('#page2').on('click', function(){
$("#a1").hide();
$('#a2').show();
$('#a2 .myrow:first-child .item:first-child').addClass('selected').trigger('click');
});
function moveRight(){
if($('.selected').next('.item').length > 0){
$('.selected').removeClass('selected').next('.item').addClass('selected')
}
}
function moveLeft(){
if($('.selected').prev('.item').length > 0){
$('.selected').removeClass('selected').prev('.item').addClass('selected')
}
}
function moveDown(){
if($('.selected').parent('.myrow').next('.myrow').length > 0){
var index = $('.selected').index();
$('.selected').removeClass('selected').parent('.myrow').next('.myrow').find('.item').eq( index ).addClass('selected');
}
}
function moveUp(){
if($('.selected').parent('.myrow').prev('.myrow').length > 0){
var index = $('.selected').index();
$('.selected').removeClass('selected').parent('.myrow').prev('.myrow').find('.item').eq( index ).addClass('selected');
}
}
});
Updated: Check this fiddle,
http://jsfiddle.net/rYvfQ/4/
$(document).ready(function () {
var listItems = $(".item");
listItems.each(function (index, value) {
if (index % 4 == 0) {
$(this).addClass('clear')
// what should i do here?
}
});
});
var el = [];
$(".pages").each(function(k,v){
el[k] = $(this).html();
});
var div = $('div.mycell');
var divselected;
$(document).on('keydown',function(e) {
var div = $('div.myrow .mycell');
switch(e.which) {
case 37: // left
if(divselected){
divselected.removeClass('selected');
next = divselected.prev();
if(next.length > 0){
divselected = next.addClass('selected');
}else{
divselected = div.eq(0).addClass('selected');
}
}else{
divselected = div.eq(0).addClass('selected');
}
break;
case 38: // up
currentindex = $('div.myrow').find('.mycell[class*="selected"]').index()
if(divselected){
divselected.removeClass('selected');
div = divselected.parent().prev().find('.mycell');
if(div.length <= 0)
{
div = divselected.parent().next().find('.mycell');
}
divselected = div.eq(currentindex).addClass('selected');
}else{
div = $('div.mycell[class*="selected"]').parent().prev().find('.mycell')
divselected = div.eq(currentindex).addClass('selected');
}
break;
case 39: // right
if(divselected){
divselected.removeClass('selected');
next = divselected.next();
if(next.length > 0){
divselected = next.addClass('selected');
}else{
divselected = div.eq(0).addClass('selected');
}
}else{
divselected = div.eq(0).addClass('selected');
}
break;
case 40: // down
currentindex = $('div.myrow').find('.mycell[class*="selected"]').index()
if(divselected){
divselected.removeClass('selected');
div = divselected.parent().next().find('.mycell');
if(div.length <= 0)
{
div = divselected.parent().prev().find('.mycell');
}
divselected = div.eq(currentindex).addClass('selected');
}else{
div = $('div.mycell[class*="selected"]').parent().next().find('.mycell')
$('div.mycell[class*="selected"]').removeClass('selected');
divselected = div.eq(currentindex).addClass('selected');
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
$('#page1').click(function(){
$(".pageslist").html(el[parseInt($(this).attr('rel'))]);
divselected="";
});
$('#page2').click(function(){
$(".pageslist").html(el[parseInt($(this).attr('rel'))]);
divselected="";
});
HTML:
<div>
<div id="page1" class="button" rel = '0'>SHOW PAGE1</div>
<div id="page2" class="button" rel = '1'>SHOW PAGE2</div>
</div>
<div class="pageslist">
<div id="a1" class="pages"> PAGE 1
<div class="myrow">
<div class="mycell item selected"></div>
<div class="mycell item"></div>
<div class="mycell item"></div>
<div class="mycell item"></div>
</div>
<div class="myrow">
<div class="mycell item"></div>
<div class="mycell item"></div>
<div class="mycell item"></div>
<div class="mycell item"></div>
</div>
</div>
<div id="a2" class="pages" hidden> PAGE 2
<div class="myrow">
<div class="mycell item selected"></div>
<div class="mycell item"></div>
<div class="mycell item"></div>
<div class="mycell item"></div>
</div>
<div class="myrow">
<div class="mycell item"></div>
<div class="mycell item"></div>
<div class="mycell item"></div>
<div class="mycell item"></div>
</div>
</div>
</div>

Categories

Resources