Change CSS Background Image for KEYBIND Javascript DIV - javascript

I am using the following to contain a div within borders.
The DIV is attached to each arrow key.
How can I change the background image of #body per each key-direction?
<script>
var pane = $('#border'),
box = $('#body'),
w = pane.width() - box.width(),
d = {},
x = 3;
function newv(v,a,b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > w ? w : n;
}
$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });
setInterval(function() {
box.css({
left: function(i,v) { return newv(v, 37, 39); },
top: function(i,v) { return newv(v, 38, 40); }
});
}, 20);
</script>
<div id="border">
<div id="body">
<div class='head'></div>
</div>
</div>
#border{position:relative; width:300px; height:300px; border:2px solid red;}
#body{position:absolute; top:140px; left:140px; width: 70px; height: 70px; background: url('/images/model.png');}
#body .head{width: 70px; height: 25px; top: 0; background: rgba(0,0,0,0.5);}

Whenever any keypress/keydown events are fired change the background-image attribute using the css method of jquery.
$('.background').css('background-image','url(images/any_image.png)');
In your case it might be something like this,
$(window).keydown(function(e) {
d[e.which] = true;
$('#body').css('background-image','url(http://hdlatestwallpapers.com/wp-content/uploads/2013/12/Tom-and-Jerry-Cartoon-Wallpaper.jpg)');
});
Not sure how you are getting the images. If you can get random images on each keydown/keyup then you can change the url and have difference backgrounds. Same goes for keyup event.

Related

Use Jquery animate to have a button move a box to the next corner

I am new to using javascript and jquery so I'm having some problems figuring this one out.
I am trying to use the animate function in jquery to move a box from one corner to the next.
The box begins on the top-left corner of the screen and upon clicking the 'go' button, it will move to the next corner (top-right).
Clicking the same 'go' button then moves the box to the next corner (bottom-right).
Clicking the 'go' button once more will move it to the next corner (bottom-left).
Clicking the 'go' button once more will move it to the next corner (top-left, which is the start).
I've included a picture to show exactly what I mean by this:
What the program should do!
So, this is what I've got so far:
$(document).ready(function () {
$('#go').click(function(){
var dest = parseInt($('#block').css('margin-left').replace('px', '')) + 100;
if (dest > 0) {
$('#block').animate({
marginLeft: '1800px'
}, 0 );
}
else {
$('#block').animate({
marginLeft: dest + 'px'
}, 0 );
}
});
});
#block {
width: 100px;
height: 100px;
background: red;
margin: 0px;
top: 0px;
left: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="block"></div>
<button id="go">» Run</button>
I've got the box to move to the top-right corner but cannot figure out how to make it now move down using the same button.
I've tried something with a toggle but it did not work. That looked something like this:
$(document).ready(function () {
$('#go').click(function(){
var toggle = 1
if (toggle == 1){
$("#block").animate({left: "80px"});
toggle = 0;
} else{
$("#block").animate({right: "80px"});
toggle = 1;
}
});
I was thinking of maybe using cases to switch between which coordinates the button will move the box to. However, I have no knowledge of how this works with jquery and the animate function.
If anyone has any other ideas or knows how to use the case switches in this scenario, I would really appreciate it and thank you in advance!
P.S. I've tried searching this answer on here for a couple of hours now and have not found much that will help me. I am hoping this question will serve to help others who are having a similar problem to mine!
Please try this example:
$(document).ready(function () {
var leftValue = window.innerWidth - 115; // 115 is a temp value
var topValue = window.innerHeight - 115;
var actionNum = 0;
var movingBlock = $('#block');
$('#go').click(function () {
if (actionNum < 4) {
actionNum++;
} else {
actionNum = 1;
}
switch (actionNum) {
case 1:
// move to the top right
movingBlock.animate({
left: leftValue + 'px',
top: 0
}, 1000);
break;
case 2:
// move to the bottom right
movingBlock.animate({
left: leftValue + 'px',
top: topValue + 'px'
}, 1000);
break;
case 3:
// move to the left bottom
movingBlock.animate({
top: topValue + 'px',
left: 0
}, 1000);
break;
case 4:
// move to the top left
movingBlock.animate({
left: 0,
top: 0
}, 1000);
break;
default:
break;
}
});
});
#block {
width: 100px;
height: 100px;
background: red;
margin: 0px;
top: 0px;
left: 0px;
position: relative;
z-index: 1;
}
#go {
z-index: 2;
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="block"></div>
<button id="go">» Run</button>
There is a multi solution for your problem ,
So I suggest some simple solution , is that you pput position absolute to your div ,
then change (annimate) the left or top of this last after checking conditions ,
you can get top left position in Jquery using .position() funcion ,
See belwon Snippet (added , 1000 milisseconde in order to show annimation transition )
var widh_annimation = "400px";
var hieght_annimation = "100px";
$(document).ready(function () {
$('#go').click(function(){
var position = $("#block").position();
var annimation = {};
if(position.left == 0 && position.top == 0) {
annimation = { left:widh_annimation};
}else if(position.left > 0 && position.top == 0) {
annimation = { top:hieght_annimation};
}else if(position.left > 0 && position.top > 0) {
annimation = { left:"0"};
}else if(position.left == 0 && position.top > 0) {
annimation = { top:"0"};
}
$('#block').animate(annimation, 1000 );
});
});
#block {
width: 100px;
height: 100px;
background: red;
margin: 0px;
top: 0px;
left: 0px;
position:absolute;
}
#go {
position:absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="block"></div>
<button id="go">» Run</button>

Javascript only add a class to an element on an interval after it's come into viewport

I have a series of images I want to transition from 0 opacity to 1 opacity when they come into the view port. I have the viewport check part done and the adding classes, however I would like them to be on an interval, so once the first 3 images come into the view port they appear 1, 2, 3 every .5seconds or so. Instead of all 3 at the same time.
here's a JS fiddle of how it works currently
reveal();
function reveal() {
var reveal = document.querySelectorAll(".reveal");
window.onscroll = function() {
for(var i = 0; i < reveal.length; i++) {
if(checkVisible(reveal[i]) === true) {
reveal[i].classList.add("fade");
}
}
}
};
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= -200);
}
https://jsfiddle.net/u04sy7jb/
I've modified your code to add a transition-delay of an additional .5 seconds for each element after the first one, in each "group" that is revealed as you scroll. I left comments in the JavaScript so you can understand the changes.
Let me know if you have any questions!
Live demo:
reveal();
function reveal() {
var reveal = document.querySelectorAll(".reveal");
window.onscroll = function() {
// start a new count each time user scrolls
count = 0;
for (var i = 0; i < reveal.length; i++) {
// also check here if the element has already been faded in
if (checkVisible(reveal[i]) && !reveal[i].classList.contains("fade")) {
// add .5 seconds to the transition for each
// additional element currently being revealed
reveal[i].style.transitionDelay = count * 500 + "ms";
reveal[i].classList.add("fade");
// increment count
count++;
}
}
}
};
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= -200);
}
.container {
width: 100%;
height: 1200px;
background-color: orange;
}
.reveal {
display: inline-block;
width: 32%;
margin: 0 auto;
height: 400px;
background-color: pink;
border: 1px solid black;
opacity: 0;
}
.fade {
opacity: 1;
transition: 1s;
}
<div class="container">
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
</div>
You could be able to stick your reveal[i].classList.add("fade"); inside of a setTimeout that executes as a function of your ith element so they show up how you're describing. Here is an example of adding short function to add the class and using it in a setTimeout to make this happen, although you could change it up to meet any additional needs.
function reveal() {
var reveal = document.querySelectorAll(".reveal");
window.onscroll = function() {
for(var i = 0; i < reveal.length; i++) {
if(checkVisible(reveal[i]) === true) {
addMyFadeClass(reveal[i], i)
}
}
}
};
function addMyFadeClass(element, i) {
setTimeout(function() {
element.classList.add("fade");
}, i * 500)
}
You can also use :nth-child CSS selectors without the need to change the JS:
.reveal:nth-child(3n+1).fade {
opacity: 1;
transition: 1s;
}
.reveal:nth-child(3n+2).fade {
opacity: 1;
transition: 1.5s;
}
.reveal:nth-child(3n).fade {
opacity: 1;
transition: 2s;
}
JSFiddle: https://jsfiddle.net/u04sy7jb/8/

How to achieve image changing on hover?

So I am trying to achieve the effect as such on this website.
(Near the bottom where you can hover over the image and it shows another as you move over it)
Any ideas? I mean I know they are just overlaying the two images, but how they then display the far image using CSS/Javascript on hover? This is beyond me. I have tried reproducing it myself with no success.
Try this:
var main = document.querySelector('.main');
var one = document.querySelector('.one');
var two = document.querySelector('.two');
main.onmousemove = function (e) {
var width = e.pageX - e.currentTarget.offsetLeft;
one.style.width = width + "px";
two.style.left = width + "px";
}
.main {
width: 200px;
height: 200px;
overflow: hidden;
position: relative;
}
.one {
background-image: url('http://www.lorempixel.com/200/200');
width: 50%;
height: 100%;
}
.two {
background-image: url('http://www.lorempixel.com/200/200/sports');
position: absolute;
left: 50%;
right: 0px;
top: 0px;
bottom: 0px;
background-position: right;
}
<div class="main">
<div class="one"></div>
<div class="two"></div>
</div>
Working Fiddle
So what's happening is, as the mouse hovers over the line, the width changes dynamically, if you inspect the element, you can see this as well.
Now, in the DOM structure, the brown car, the one being hidden is before the top image. So to achieve this, you can position the brown car absolutely, so it goes right behind the next image, and with javascript or jQuery add a listener for hover, on the image or that middle line that is used on the site, that will change the width of the top image (the silver one) in respect to the position of the mouse in the block of the image.
Essentially, the width of the background image should change by percentage to how far the mouse is from the left of the DIV, by percent i.e. if the mouse is at the middle, the width should be 50%.
Here is the js they use to do it, right from their site (I uncompressed it)
var ImageSlider = ImageSlider || {};
ImageSlider.Public = function(t) {
"use strict";
var e = t(".image-compare-tool"),
i = t(".image-compare-images"),
o = t(".image-compare-top img"),
a = (t(".image-compare-bottom img"), function(e) {
e.preventDefault();
var i, o = t(this).find(".image-compare-top"),
a = t(this).find(".image-compare-bottom img")[0],
n = a.getBoundingClientRect();
i = "mousemove" == e.originalEvent.type ? (e.pageX - n.left) / a.offsetWidth * 100 : (e.originalEvent.touches[0].pageX - n.left) / a.offsetWidth * 100, 100 >= i && o.css({
width: i + "%"
})
}),
n = function() {
i.each(function() {
t(this).on("mousemove", a), t(this).on("touchstart", a), t(this).on("touchmove", a)
})
},
m = function() {
o.each(function() {
var e = t(this).attr("src"),
i = t(this).parent();
i.css("background-image", "url(" + e + ")")
})
},
c = function() {
n(), m()
},
r = function() {
e.length > 0 && c()
};
r()}(jQuery);
If you look at html sources (Ctr + Shift + I in Chrome) you can see this element
<div class="image-compare-tool ICT-theverge">
<div class="image-compare-images">
<div class="image-compare-bottom"><img src="http://cdn2.vox-cdn.com/uploads/chorus_asset/file/2455624/khyzyl-saleem-plain-copylow.0.jpg"></div>
<div class="image-compare-top" style="width: 6.158357771261%; background-image: url(http://cdn0.vox-cdn.com/uploads/chorus_asset/file/2455620/khyzyl-saleem-plain-copylow1.0.jpeg);"><img src="http://cdn0.vox-cdn.com/uploads/chorus_asset/file/2455620/khyzyl-saleem-plain-copylow1.0.jpeg"></div>
</div>
</div>
So here are images! So next you need to look at css.
.image-compare-tool
{
max-width:100%;
width:100%;
z-index:999;
margin:0 auto 1.5em 0;
}
.image-compare-images
{
font-size:0;
position:relative;
height:100%;
-ms-touch-action:none;
-webkit-touch-callout:none;
-webkit-user-select:none;
}
.image-compare-images:hover
{
cursor:col-resize;
}
.image-compare-images img
{
display:block;
height:auto;
width:100%;
}
.image-compare-top,.image-compare-bottom
{
z-index:0;
height:100%;
}
.image-compare-top
{
background-size:cover;
height:100%;
left:0;
position:absolute;
top:0;
width:50%;
}
.image-compare-top:after
{
background-color:#fff;
content:'';
height:50px;
left:calc(100%-5px);
top:calc(50%-25px);
position:absolute;
width:10px;
}
.image-compare-top img
{
display:none;
}
.ICT-SBNation .image-compare-top:after
{
background-color:#c52126;
}
.ICT-SBNation .image-compare-top:before
{
background-color:#c52126;
content:'';
height:100%;
left:calc(100%-2.5px);
top:0;
position:absolute;
width:5px;
}
.ICT-TheVerge .image-compare-top:after
{
background-color:#fa4b2a;
}
.ICT-TheVerge .image-compare-top:before
{
background-color:#fa4b2a;
content:'';
height:100%;
left:calc(100%-2.5px);
top:0;
position:absolute;
width:5px;
}
.ICT-Polygon .image-compare-top:after
{
background-color:#ff0052;
}
.ICT-Polygon .image-compare-top:before
{
background-color:#ff0052;
content:'';
height:100%;
left:calc(100%-2.5px);
top:0;
position:absolute;
width:5px;
}
.image-compare-top:before,.ICT-Vox .image-compare-top:before
{
background-color:#fff;
content:'';
height:100%;
left:calc(100%-2.5px);
top:0;
position:absolute;
width:5px;
}
Here wea! You can implement same stuff by just including css and making same html structure and classes with just changing img paths...
And finally the js that i brazenly stole from the answer above:
var ImageSlider = ImageSlider || {};
ImageSlider.Public = function (t) {
"use strict";
var e = t(".image-compare-tool"),
i = t(".image-compare-images"),
o = t(".image-compare-top img"),
a = (t(".image-compare-bottom img"), function (e) {
e.preventDefault();
var i, o = t(this).find(".image-compare-top"),
a = t(this).find(".image-compare-bottom img")[0],
n = a.getBoundingClientRect();
i = "mousemove" == e.originalEvent.type ? (e.pageX - n.left) / a.offsetWidth * 100 : (e.originalEvent.touches[0].pageX - n.left) / a.offsetWidth * 100, 100 >= i && o.css({
width: i + "%"
})
}),
n = function () {
i.each(function () {
t(this).on("mousemove", a), t(this).on("touchstart", a), t(this).on("touchmove", a)
})
},
m = function () {
o.each(function () {
var e = t(this).attr("src"),
i = t(this).parent();
i.css("background-image", "url(" + e + ")")
})
},
c = function () {
n(), m()
},
r = function () {
e.length > 0 && c()
};
r()
}(jQuery);
And the working JSFiddle: http://jsfiddle.net/9gf59k00/
And my good luck...
$('img').on('mousemove', function(){
var imgsrc = $(this).attr('src');
if(imgsrc == 'img1.png'){
$(this).attr('src','img2.png');
}else{
$(this).attr('src','img1.png');
}
});
You can do this without javascript,
JSfiddle - http://jsfiddle.net/k4915wwm/
Just…
div:hover {
background:url("newImage.jpg");
}

(HTML) JavaScript Collapsible Menu Error

http://jsfiddle.net/xNnQ5/
I am trying to use JavaScript (and HTML) to create a collapsible menu (c_menu) for my website. I would like it to be opened when the user clicks on the div menu_open, and to close when the user clicks menu_close. However, when I load the page, all that happens is the menu simply scrolls up, as if I have clicked menu_close, which I haven't. What should I do?
Code:
index.html (Only a snippet)
<style type = "text/css">
#c_menu {
position: absolute;
width: 435px;
height: 250px;
z-index: 2;
left: 6px;
top: 294px;
background-color: #0099CC;
margin: auto;
</style>
<div id="menu_open"><img src="images/open.jpg" width="200" height="88" /></div>
<input type="button" name="menu_close" id="menu_close" value="Close"/>
<div id="c_menu"></div>
<script type = "text/javascript" src = "menu.js"> </script>
menu.js (Full code)
document.getElementById("c_menu").style.height = "0px";
document.getElementById("menu_open").onclick = menu_view(true);
document.getElementById("menu_close").onclick = menu_view(false);
function menu_view(toggle)
{
if(toggle == true)
{
document.getElementById("c_menu").style.height = "0px";
changeheight(5, 250, 0);
}
if(toggle == false)
{
document.getElementById("c_menu").height = "250px";
changeheight(-5, 0, 250);
}
}
function changeheight(incr, maxheight, init)
{
setTimeout(function () {
var total = init;
total += incr;
var h = total + "px";
document.getElementById("c_menu").style.height = h;
if (total != maxheight) {
changeheight(incr, maxheight, total);
}
}, 5)
}
Try this:
document.getElementById("menu_open").onclick = function() {menu_view(true)};
document.getElementById("menu_close").onclick = function() {menu_view(false)};
When you define the function with a parenthesis ( ...onclick = menu_view(true) ), the function is called automatically.
When you have a function with no parameters, you can use it like you did, but without the parenthesis:
document.getElementById("menu_open").onclick = menu_view;
document.getElementById("menu_close").onclick = menu_view;

How to repeat function onclick - Javascript

So, I'm trying to make an animation in JavaScript (I want a navigation bar to pull down when I click it). The problem is that every time I click this navigation bar, it only moves down one pixel. How do I make it to where I can make the "Move" function repeat over and over so that it realizes the navigation bar is below "0", and move it up? Here's the code I have atm:
var i = -43 //original position of div
function Move(x)
{
if (i < 0)
{
i++;
x.style.top = i + "px";
}
}
function setPosition(x)
{
setInterval(Move(x), 500);
}
P.S. I have the "div onclick" equal to "setInterval(this)"
I would use a setTimeout() (so you don't have to worry about canceling the setInterval()), and note the use of an anonymous function (function(){}) for the first argument of the setTimeout() call:
#slider {
position: absolute;
top: -43px;
left: 200px;
width: 200px;
height: 50px;
border: 1px solid blue;
background: #dff;
}
<div id='slider'>This is a slidout</div>
<div id="clicker">Click me!</div>
var slider = document.getElementById('slider'),
clicker = document.getElementById('clicker');
clicker.onclick = function(){
Move(slider, -43);
};
function Move(x, i)
{
if (i < 0)
{
i++;
x.style.top = i + "px";
setTimeout(function(){
Move(x, i);
}, 50);
}
}
http://jsfiddle.net/h2C3A/

Categories

Resources