I have this simple JavaScript code that is supposed to side a div in and a div out. it is working perfectly when it comes to sliding in. By working perfectly is sliding the div easily. However when you click slideout the div just disappears from the browser. I don't know why and I cant find a fault. My code is here
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
function slideIt()
{
var stopPosition = 50;
var slidingDiv = "";
slidingDiv = document.getElementById("d3");
if (parseInt(slidingDiv.style.left) < stopPosition )
{
slidingDiv.style.left = parseInt(slidingDiv.style.left) + 2 + "px";
setTimeout(slideIt, 1);
}
}
function slideOut()
{
var startPosition =-150;
var slidingDiv = "";
slidingDiv = document.getElementById("d4");
if (parseInt(slidingDiv.style.left) > startPosition )
{
slidingDiv.style.left = parseInt(slidingDiv.style.left) - 2 + "px";
setTimeout(slideOut(), 1);
}
}
</script>
<div id="d1" onclick="slideIt();">Slide in</div>
<div id="d2" onclick="slideOut();">Slide out</div>
<div id="d3" style="position: absolute; left:-150px; top:300px" >horizontally sliding div</div>
<div id="d4" style="position: absolute; left:150px; top:300px">horizontally sliding div</div>
</body>
</html>
You don't need to invoke slideOut in the second timeout. Remove the parentheses.
setTimeout(slideOut, 1);
Here is a demonstration: http://jsfiddle.net/cctqf/
Related
I am trying to get the ball element to both move and shrink towards the goals on mouse click.
I have created a function that grabs the coordinates of the mouse click in the goals, however I have been struggling with the ball animation.
I thought about using keyframes, but I don't know how to use keyframes in JavaScript.
I also tried doing a transform - which I know wouldn't work, but tried as you can see in the move() function.
This is my javascript/html file
function goal(){
var score = getScore();
increaseDifficulty(score)
document.getElementById("score").innerHTML = score + 1 ;
var b = getShotCordinates();
move(b[0],b[1]);
}
function save(){
resetScore();
}
function resetScore(){
document.getElementById("score").innerHTML = 0;
}
function getScore(){
return parseInt(document.getElementById("score").innerHTML);
}
function move(x,y){
const fxMove = `translate(${x}px, ${y}px);`;
const fxAnim = `transition: transform 0.5s; transform: translate(0, 0);`;
document.getElementById("ball").style.transform = translate(x,y);
}
function getShotCordinates(){
var e = window.event;
var Cordinates = [e.clientX, e.clientY];
console.log(Cordinates[0] + " - " + Cordinates[1])
return Cordinates;
}
<BODY>
<div id="canvas" class="field">
<div id="goals" class="goals" onclick="goal()">
</div>
<div id="goalkeeper" onclick="save()">
</div>
<div id="kick-off">
<div id="ball" class="ball">
</div>
</div>
<div id="score-container">
<div id="counter">
<h1 class="counter-text">Score</h1>
<h1 class="counter-score" id="score">0</h1>
</div>
</div>
</div>
<script src='js/script.js'></script>
</BODY>
Just in case, this is my canvas/UI
If you are looking for something like this:
const div = document.querySelector("div");
document.addEventListener("click", (e)=>{
console.log(e)
div.style.top = e.clientY + "px";
div.style.left = e.clientX + "px";
})
div{
width:50px;
height:50px;
background:red;
border-radius:50%;
position:absolute;
transition:.3s;
transform:translate(-50%, -50%);
}
<div></div>
Just give the ball position absolute, and on every click event change the top and the left of the ball with javascript.
I want to hide all elements but the first one so I use $(".item:not(:eq(0))").fadeOut();
I have elements with the same class "item":
<div class="item">First Item</div>
<div class="item">Second Item</div>
<div class="item">Third Item</div>
<div class="item">Fourth Item</div>
Then when I scroll to the next element which could be "second , third,fourth item" , I want to show it
I tried using :
function isScrolledIntoView(elem)
{
var centerY = Math.max(0,((jQuery(window).height()-
jQuery(elem).outerHeight()) / 2)
+ jQuery(window).scrollTop());
var elementTop = jQuery(elem).offset().top;
var elementBottom = elementTop + jQuery(elem).height();
return elementTop <= centerY && elementBottom >= centerY;
}
jQuery(window).on("scroll resize", function() {
jQuery(".news:not(:eq(0))").each(function(index, element) {
if (isScrolledIntoView(element)) {
jQuery(element).fadeIn(10000);
}
});
});
But it doesn't work with my method because the height of the body changes on showing the next item "Second Item" , So All the items are shown when I scroll to the "Second Item" or any other item.
How to hide the items but the first one and then fadIn() each on scrolling to it ?
This is using offset() in jquery. This demo will trigger function if
your element is completely in your viewport.
Tip:You need to take care of inner as well as outer height of element.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
body{
height:200vh;
}
#test {
top: 100vh;
padding: 10px;
width: 300px;
position: relative;
border: 1px solid black;
height:100;
}
</style>
</head>
<body>
<p>scroll to test</p>
<div id="test">
<p>Click the button to get offsetTop for the test div.</p>
</div>
<script>
$(document).ready(function(){
$(window).scroll(function(){
var x = $("#test").offset();
var height1 = $("#test").outerHeight();
var y = document.documentElement.scrollTop;
var z = (x.top + height1) - y;
if(z < $(window).height()){
alert("fumction");
}
});
});
</script>
</body>
</html>
It will be more easy to use the combination of waypoint.js and animate.css.
Add animated class to every element to be animated. You can use any of the animate.css effects.
Change the offset { offset: '80%' } to control when the animation can start.
<div class="animated waypoint-slideup">
</div>
$('.waypoint-slideup').waypoint(function () {
$(this).addClass('slideInUp');
}, { offset: '80%' });
Use this in the css file
.waypoint-slideup{
opacity:0;}
.waypoint-slideup.slideInUp{
opacity:1;}
I need a jQuery background fader from background to background.
I have a base to go off, but have had no success.
I have all the proper libraries included, I have triple checked.
//Array of images which you want to show: Use path you want.
var images = new Array('img/bg_0.jpg', 'img/bg_1.jpg', 'img/bg_2.jpg');
var nextimage = 0;
doSlideshow();
function doSlideshow() {
if (nextimage >= images.length) {
nextimage = 0;
}
$('.face')
.css('background-image', 'url("' + images[nextimage++] + '")')
.fadeIn(500, function() {
setTimeout(doSlideshow, 1000);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="face" style="background-image: url('img/bg_5.jpg');" class="face">
<div class="face-body">
<div class="container text-center">
<h1 class="face-title one">
<?php echo SRV_NAME; ?>
</h1>
<h2 class="face-subtitle">
<?php echo SRV_SLOGAN; ?>
</h2>
</div>
</div>
</section>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js"></script>
You have to use an <img> element if you wish to fade in/out.
A background can't be animated. Only elements can. A background isn't an element, it is a property of an element.
So what I suggest here is to get rid of the background idea and use an absolute positionned image element (to have it behind your text, as a background does).
Have a look at the snippet below:
//Array of images which you want to show: Use path you want.
var images = new Array('http://www.petmd.com/sites/default/files/hypoallergenic-cat-breeds.jpg', 'https://cmeimg-a.akamaihd.net/640/clsd/getty/c64f76dc20c246ca88ee180fe4b4b781', 'https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a.jpeg');
var nextimage = 0;
doSlideshow();
function doSlideshow() {
if (nextimage >= images.length) {
nextimage = 0;
}
$('.face')
.fadeOut(500,function(){
$(this).attr('src', images[nextimage++])
.fadeIn(500, function() {
setTimeout(doSlideshow, 1000);
});
});
}
.face{
position:absolute;
top:0;
left:0;
z-index:-1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="face">
<img src="https://www.petmd.com/sites/default/files/what-does-it-mean-when-cat-wags-tail.jpg" class="face">
<div class="face-body">
<div class="container text-center">
<h1 class="face-title one">
NAME
</h1>
<h2 class="face-subtitle">
SLOGAN
</h2>
</div>
</div>
</section>
<body>
<div id = "SiteContainer">
<div id = "NavigationButtons"></div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition();">x</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition();">y</div>
<div id = "VideoWrapper">
<div id = "SlideShowItem">
<img src="Images/A.png" alt="A"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/B.png" alt="B"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/C.png" alt="C" ></img>
</div>
</div>
</div>
</div>
<script>
var wrapper = document.querySelector("#VideoWrapper");
function setPosition(e)
{
if(e.target.name = "forward")
{
if!(wrapper.style.left = "-200%")
{
wrapper.style.left = wrapper.style.left - 100%;
}
}
else
{
if(e.target.name = "back")
{
if!(wrapper.style.left = "0%")
{
wrapper.style.left = wrapper.style.left + 100%;
}
}
}
}
</script>
</body>
Hi, I am very new to javascript. What I am trying to do, is change the x-position of a div when another div (NavigationForward or NavigationBackward) is clicked. However it does not appear to do anything at all. Basically if the div with name forward is clicked, I want to translate the VideoWrapper -100% from it's current position and +100% when "back". The css div itself VideoWrapper has a width of 300%. Inside this div as you can see is a SlideShowItem which is what will change. Perhaps I am adding and subtracting 100% the wrong way?
EDIT:
Thanks everyone for helping me out with this...I had just one more query, I am trying to hide the arrows based on whether the wrapper is at the first slide or the last slide. If its on the first slide, then I'd hide the left arrow div and if it's on the last, I'd hide the right arrow, otherwise display both of em. Ive tried several ways to achieve this, but none of em work, so Ive resorted to using copies of variables from the function that works. Even then it does not work. It appears that my if and else if statements always evaluate to false, so perhaps I am not retrieving the position properly?
function HideArrows()
{
var wrapper2 = document.getElementById("VideoWrapper");
var offset_x2 = wrapper2.style.left;
if(parseInt(offset_x2,10) == max_x)
{
document.getElementById("NavigationForward").display = 'none';
}
else if(parseInt(offset_x2,10) == min_x)
{
document.getElementById("NavigationBackward").display = 'none';
}
else
{
document.getElementById("NavigationForward").display = 'inline-block';
document.getElementById("NavigationBackward").display = 'inline-block';
}
}
//html is the same except that I added a mouseover = "HideArrows();"
<div id = "ShowReelContainer" onmouseover="HideArrows();">
To achieve this type o slider functionality your div VideoWrapper must have overflow:hidden style, and your SlideShowItemdivs must have a position:relative style.
Then to move the slides forward or backward you can use the style left which allows you to move the divs SlideShowItem relative to it's parent VideoWrapper.
I've tested this here on JSFiddle.
It seems to work as you described in your question, although you may need to do some adjustments, like defining the width of your slides, how many they are and so on.
For the sake of simplicity, I defined them as "constants" on the top of the code, but I think you can work from that point on.
CSS
#VideoWrapper{
position:relative; height:100px; white-space:nowrap;width:500px;
margin-left:0px; border:1px solid #000; overflow:hidden; }
.SlideShowItem{
width:500px; height:100px;display:inline-block;position:relative; }
#NavigationForward, #NavigationBackward{
cursor:pointer;float:left; background-color:silver;margin-right:5px;
margin-bottom:10px; text-align:center; padding:10px; }
HTML
<div id = "SiteContainer">
<div id = "NavigationButtons">
</div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition('back');">prev</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition('forward');">next</div>
<div style="clear:both;"></div>
<div id = "VideoWrapper">
<div class= "SlideShowItem" style="background-color:blue;">
Slide 1
</div>
<div class = "SlideShowItem" style="background-color:yellow;">
Slide 2
</div>
<div class = "SlideShowItem" style="background-color:pink;">
Slide 3
</div>
</div>
</div>
</div>
JavaScript
var unit = 'px'; var margin = 4; var itemSize = 500 + margin; var itemCount = 3; var min_x = 0; var max_x = -(itemCount-1) * itemSize;
function setPosition(e) {
var wrapper = document.getElementById("VideoWrapper");
var slides = wrapper.getElementsByTagName('div');
var offset_x = slides[0].style.left.replace(unit, '');
var curr_x = parseInt(offset_x.length == 0 ? 0 : offset_x);
if(e == "forward")
{
if(curr_x <= max_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + -itemSize) + unit;
}
else if(e == "back")
{
if(curr_x >= min_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + itemSize) + unit;
} }
After you analyze and test the code, I don't really know what's your purpose with this, I mean, you maybe just playing around or trying to develop something for a personal project, but if you are looking for something more professional avoid to create things like sliders on your own, as there are tons of plugins like this available and well tested out there on the web.
Consider using jQuery with NivoSlider, it works like a charm and is cross browser.
I would recommend using jQuery, this will reduce your coding by quite a bit. Can read more here: http://api.jquery.com/animate/
I've created a simple fiddle for you to take a look at. This example uses the .animate() method to reposition two div elements based on the CSS 'left' property.
CSS:
#container {
position: absolute;
left: 1em;
top: 1em;
right: 1em;
bottom: 1em;
overflow: hidden;
}
#one, #two {
position: absolute;
color: white;
}
#one {
background: pink;
width: 100%;
top:0;
bottom:0;
}
#two {
background: blue;
width: 100%;
left: 100%;
top:0;
bottom:0;
}
HTML:
<div id="container">
<div id="one">Div One</div>
<div id="two">Div Two</div>
</div>
JavaScript/jQuery:
var one, two, container;
function animateSlides(){
one.animate({
left : '-100%'
}, 1000, function(){
one.animate({
left : 0
}, 1000);
});
two.animate({
left : 0
}, 1000, function(){
two.animate({
left:'100%'
}, 1000);
});
};
$(function(){
one = $('#one');
two = $('#two');
container = $('#container');
setInterval(animateSlides, 2000);
});
JSFiddle Example: http://jsfiddle.net/adamfullen/vSSK8/3/
I am new person in Front End Development and i am facing one major problem is that i have 3 images placed on each others and now i want to move one image so the other image comes up and then it goes and third image comes up after some interval of time.
I want three images on same position in my site but only wants to see these three images one after one after some interval of time.
Please help how i can do this??
May i use marquee property or javascript???
Non-jQuery Option
If you don't want to go down the jquery route, you can try http://www.menucool.com/javascript-image-slider. The setup is just as easy, you just have to make sure that your images are in a div with id of slider and that div has the same dimensions as one of your images.
jQuery Option
The jQuery cycle plugin will help you achieve this. It requires jquery to work but it doesn't need much setting up to create a simple sliple slideshow.
Have a look at the 'super basic' demo:
$(document).ready(function() {
$('.slideshow').cycle({
fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
});
});
It has many options if you want something a bit fancier.
Here you go PURE JavaScript solution:
EDIT I have added image rotation... Check out live example (link below)
<script>
var current = 0;
var rotator_obj = null;
var images_array = new Array();
images_array[0] = "rotator_1";
images_array[1] = "rotator_2";
images_array[2] = "rotator_3";
var rotate_them = setInterval(function(){rotating()},4000);
function rotating(){
rotator_obj = document.getElementById(images_array[current]);
if(current != 0) {
var rotator_obj_pass = document.getElementById(images_array[current-1]);
rotator_obj_pass.style.left = "-320px";
}
else {
rotator_obj.style.left = "-320px";
}
var slideit = setInterval(function(){change_position(rotator_obj)},30);
current++;
if (current == images_array.length+1) {
var rotator_obj_passed = document.getElementById(images_array[current-2]);
rotator_obj_passed.style.left = "-320px";
current = 0;
rotating();
}
}
function change_position(rotator_obj, type) {
var intleft = parseInt(rotator_obj.style.left);
if (intleft != 0) {
rotator_obj.style.left = intleft + 32 + "px";
}
else if (intleft == 0) {
clearInterval(slideit);
}
}
</script>
<style>
#rotate_outer {
position: absolute;
top: 50%;
left: 50%;
width: 320px;
height: 240px;
margin-top: -120px;
margin-left: -160px;
overflow: hidden;
}
#rotate_outer img {
position: absolute;
top: 0px;
left: 0px;
}
</style>
<html>
<head>
</head>
<body onload="rotating();">
<div id="rotate_outer">
<img src="0.jpg" id="rotator_1" style="left: -320px;" />
<img src="1.jpg" id="rotator_2" style="left: -320px;" />
<img src="2.jpg" id="rotator_3" style="left: -320px;" />
</div>
</body>
</html>
And a working example:
http://simplestudio.rs/yard/rotate/rotate.html
If you aim for good transition and effect, I suggest an image slider called "jqFancyTransitions"
<html>
<head>
<script type="text/javascript">
window.onload = function(){
window.displayImgCount = 0;
function cycleImage(){
if (displayImgCount !== 0) {
document.getElementById("img" + displayImgCount).style.display = "none";
}
displayImgCount = displayImgCount === 3 ? 1 : displayImgCount + 1;
document.getElementById("img" + displayImgCount).style.display = "block";
setTimeout(cycleImage, 1000);
}
cycleImage();
}
</script>
</head>
<body>
<img id="img1" src="./img1.png" style="display: none">
<img id="img2" src="./img2.png" style="display: none">
<img id="img3" src="./img3.png" style="display: none">
</body>
</html>
Fiddle: http://jsfiddle.net/SReject/F7haV/
arrayImageSource= ["Image1","Image2","Image3"];
setInterval(cycle, 2000);
var count = 0;
function cycle()
{
image.src = arrayImageSource[count]
count = (count === 2) ? 0 : count + 1;
}
Maybe something like this?