Selecting proper elements of a div by navigation keys - javascript

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>

Related

jquery scrolltop stay position after response

I wrote a code to view the chat history. Everything works fine, but I realized that. When you scroll up the div to view the history, old posts are displayed at a time. I've added this code $("#messages").scrollTop(200); to be able to continue scrolling, but this should not be. When you want to view old messages in apps like whatsapp or facebook, you can continue to scroll up for viewing old messages.
What am I supposed to do to stay position after response?
Here is DEMO page.
$(document).ready(function() {
var logDown = $(".chatContainer");
logDown.animate({ scrollTop: logDown.prop("scrollHeight") }, 0);
var messages = ''; // New Posts are in demo
var scrollLoading = true;
$("#messages").scrollTop($("#messages")[0].scrollHeight);
$("#messages").on("scroll", function() {
if (scrollLoading && $("#messages").scrollTop() == 0) {
$("#messages").prepend(messages);
$("#messages").scrollTop(200);
}
});
});
now I understood, i solved it by subtracting the old-height from the new height and set this "old-position" as scrolltop
var old_height,new_height;
$("#messages").on("scroll", function() {
if (scrollLoading && $("#messages").scrollTop() == 0) {
old_height = $("#messages")[0].scrollHeight;
$("#messages").prepend(messages);
new_height = $("#messages")[0].scrollHeight;
$("#messages").scrollTop(new_height - old_height);
}
});
works optimal for me
If I understood your problem you don't want to scroll to the top of the messages at every batch of prepends.
I managed to pull a version without jQuery and using window.requestAnimationFrame for good scroll performance.
Just my $0.02 on the problem.
var container = document.querySelector("#messages");
container.scrollTop = container.scrollHeight;
container.addEventListener("scroll", function(e) {
last_known_scroll_position = e.target.scrollTop;
var ticking;
if (!ticking) {
window.requestAnimationFrame(function() {
if (last_known_scroll_position == 0) {
var delta = e.target.scrollHeight;
for (var i = 1; i <= 5; i++) {
var message = document.createElement("DIV");
message.textContent = "Message Here";
message.classList.add("message", "red");
e.target.prepend(message);
}
delta = e.target.scrollHeight - delta;
e.target.scrollTop = delta;
ticking = false;
}
});
ticking = true;
}
});
DIV.chatContainer {
height: 200px;
overflow: auto;
}
.message {
margin-bottom:10px;
}
.red {
background-color:red;
}
<div class="container">
<div class="chatContainer" id="messages">
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE last</div>
</div>
</div>

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

Movement Not Being Stopped

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

Change an objects color after scrolling

I want a make a object which can change color after scrolling (down) 100px and change back to default after scrolling back (up). I'm using this code but not working
jQuery:
$(window).scroll(function() {
//After scrolling 100px from the top...
if ( $(window).scrollTop() >= 100 ) {
$('#menu').css('background', '#fff');
//Otherwise remove inline styles and thereby revert to original stying
} else {
$('#menu').removeAttr('style');
}
});​
and my html:
<body>
<table>
<tr>
<td id="menu" class="title">
TITLE
</td>
<td style="width:40px;">
<div class=" ico">
<img src="search.svg" alt="search" style="width: 25px;" />
</div>
</td>
<td style="width: 40px;">
<div class=" ico">
<img src="menu.svg" alt="search" style="width: 25px;"/>
</div>
</td>
</tr>
</table>
</body>
Here you go :
$(function(){
var navColors = ['red', 'blue'];
var changeNavState = function(nav, newStateIndex) {
nav.data('state', newStateIndex).stop().css({
backgroundColor : navColors[newStateIndex]
});
};
var boolToStateIndex = function(bool) {
return bool * 1;
};
var maybeChangeNavState = function(nav, condState) {
var navState = nav.data('state');
if (navState === condState) {
changeNavState(nav, boolToStateIndex(!navState));
}
};
$('#header_nav').data('state', 1);
$(window).scroll(function(){
var $nav = $('#header_nav');
if ($(document).scrollTop() > 100) {
maybeChangeNavState($nav, 1);
} else {
maybeChangeNavState($nav, 0);
}
});
});
http://jsfiddle.net/2rqp6r6z/
i am using this code for stick top menu
you can customize it for your self and if you couldn't just say then i change it my self but if you , yourself do it is better
<script>
$('.top-menu').addClass('original').clone().insertAfter('.top-menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide();
scrollIntervalID = setInterval(stickIt, 10);
function stickIt() {
var orgElementPos = $('.original').offset();
orgElementTop = orgElementPos.top;
if ($(window).scrollTop() >= (orgElementTop)) {
orgElement = $('.original');
coordsOrgElement = orgElement.offset();
leftOrgElement = coordsOrgElement.left;
widthOrgElement = orgElement.css('width');
$('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement+'px').show();
$('.original').css('visibility','hidden');
} else {
$('.cloned').hide();
$('.original').css('visibility','visible');
}
}
</script>

Sticky box jQuery

I have this code:
http://jsfiddle.net/k56yR/1/
but when the browser scrollbar is down and begin to top #sticky trembles, anyone know how to fix this?
This is jQuery code:
$(function(){ // document ready
if (!!$('#sticky').length) { // make sure "#sticky" element exists
var el = $('#sticky');
var stickyTop = $('#sticky').offset().top; // returns number
var footerTop = $('#footer').offset().top; // returns number
var stickyHeight = $('#sticky').height();
var limit = footerTop - stickyHeight - 20;
$(window).scroll(function(){ // scroll event
var windowTop = $(window).scrollTop(); // returns number
if (stickyTop < windowTop){
el.css({ position: 'fixed', top: 0 });
}
else {
el.css('position','static');
}
if (limit < windowTop) {
var diff = limit - windowTop;
el.css({top: diff});
}
});
}
});​
<div class="wrapper">
<div class="results">
</div>
<header>
Header
<span></span>
</header>
<div class="left">
<span class="top"></span>
<div class="nosticky">Nosticky</div>
<div class="sticky">
<span class="top"></span>
<div class="bloc bloc1">
Bloc 1<br>
<span></span>
</div>
<div class="bloc bloc2">
Bloc 2
</div>
<span class="bottom"></span>
</div>
<span class="bottom"></span>
</div>
<div class="right">
Content
<span></span>
</div>
<div class="footer">
Footer
</div>
</div>
<script>
var sticky_offsettop = $('.sticky').offset().top;
var sticky_height = $('.sticky').height();
var sidebar_height = $('.left').height();
var empty_space_left = sidebar_height - sticky_height;
var sidebar_offsettop = $('.left').offset().top;
var sidebar_bottom_offsettop = (sidebar_offsettop+sidebar_height);
var margintotop = 20;
$(window).scroll(function() {
var window_scrolltop = $(window).scrollTop();
var window_scrolltop_margin = (window_scrolltop+margintotop);
var realtime_sidebar_bottom_offsettop = (sidebar_bottom_offsettop - window_scrolltop);
var sticky_height_realtime = $('.sticky').height();
if(window_scrolltop_margin >= sticky_offsettop ){
$('.bloc').css('background', '#ddd');
$('.sticky').css('position', 'sticky').css('top', '20px').css('bottom', 'initial');
}
if(sticky_offsettop > window_scrolltop_margin ){
$('.bloc').css('background', '#ddd');
$('.sticky').css('position', 'relative').css('top', 'initial').css('bottom', 'initial');
}
if(sticky_height_realtime >= realtime_sidebar_bottom_offsettop ){
$('.bloc').css('background', '#ddd');
$('.sticky').css('position', 'absolute').css('top', 'initial').css('position', 'absolute').css('bottom', '0');
}
});
<script>
here is an example i've done to achieve it : https://jsfiddle.net/cuopyL51/

Categories

Resources