Change DIV margin on interval - javascript

I am trying to change the margin of each element, using setAttribute.
How can I able to use my variable dist "distance" to decrease value until 10, every after delay "interval"?
var dist=200; var speed = 2000;
function slideLeft(x){
dist--;
slideSet[x].setAttribute("style","margin-right:"+dist+"px;");
setTimeout(slideLeft(x), delay);
}
Take these style and elements for example...
.widiv { margin-right:200px; }
<div>
<div class="widiv" ></div>
<div class="widiv" ></div>
</div>
Thanks a lot.

Here's your code with some changes: See fiddle http://jsfiddle.net/chrismoutray/4p3xX/
var dist = 200, delay = 500,
slideSet = document.getElementsByTagName('div');
function slideLeft(x) {
dist--;
if (dist < 0) return;
slideSet[x].setAttribute("style", "margin-right:" + dist + "px;");
setTimeout(function() {
slideLeft(x);
}, delay);
}
slideLeft(1);
With a few additions to the styling:
.widiv {
margin-right:200px;
float:left;
width: 100px;
border: 1px solid black;
height: 100px; }
The main differences are that when calling setTimeout I'm using a function delegate (function() { <your code here> }) to call the slideLeft method so that x variable is used correctly - I don't think you can pass a statement into setTimeout without doing it this way.
Also in styling the divs I made sure to include a float left other wise the change to margin right doesn't make sense - should this be margin left instead?

Related

Using .outerWidth() & .outerHeight() with the 'resize' event to center a child element in parent

I am attempting to write some JavaScript code that will allow me to center a child element within it's parent using padding. Then using the same function to recalculate the spacing using the 'resize' event. Before you start asking me why i am not doing this with CSS, this code is only a small part of a larger project. I have simplified the code as the rest of the code works and would only serve to confuse the subject.
Calculating the space - This is the function that caculates the amount of space to be used on either side of the child element.
($outer.outerWidth() - $inner.outerWidth()) / 2;
($outer.outerHeight() - $inner.outerHeight()) / 2;
The problem
Although i have successfully managed to get the desired results with margin. Padding is causing me problems.
It appears to be increasing the width on the outer element when resized
It does not center the child element perfectly (there appears to be an offset)
The inner element collapses on resize and becomes invisible.
I realize that there may be some fundamentals regarding padding that are causing my problems however after numerous console logs and observing the data returned i still can't put my finger on the problem. Any suggestion would be very welcome. It may turn out that this is not feasible at all.
HTML
<div id="demo" class="outer">
<div class="inner">
</div>
</div>
CSS
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
.outer {
width:97%;
height:400px;
border:1px solid black;
margin:20px;
}
.inner {
width:40%;
height:100px;
background-color:grey;
}
JAVASCRIPT
var $outer = $(".outer");
var $inner = $(".inner");
var getSpace = function(axis) {
if (axis.toLowerCase() == "x") {
return ($outer.outerWidth() - $inner.outerWidth()) / 2;
} else if (axis.toLowerCase() == "y") {
return ($outer.outerHeight() - $inner.outerHeight()) / 2;
}
}
var renderStyle = function(spacingType) {
var lateralSpace = getSpace("x");
var verticalSpace = getSpace("y");
var $element;
if (spacingType == "padding") {
$element = $outer;
} else if (spacingType == "margin") {
$element = $inner;
}
$.each(["top", "right", "bottom", "left"], function(index, direction) {
if (direction == "top" || direction == "bottom") {
$element.css(spacingType + "-" + direction, verticalSpace);
}
else if (direction == "right" || direction == "left") {
$element.css(spacingType + "-" + direction, lateralSpace);
}
});
};
var renderInit = function() {
$(document).ready(function() {
renderStyle("padding");
});
$(window).on("resize", function() {
renderStyle("padding");
});
}
renderInit();
EXAMPLE - link
Although I completely disagree with this approach to horizontally centring an element, hopefully this will help you on your way.
Fiddle: https://jsfiddle.net/0uxx2ujg/
JavaScript:
var outer = $('.outer'), inner = $('.inner');
function centreThatDiv(){
var requiredPadding = outer.outerWidth() / 2 - (inner.outerWidth() / 2);
console.log(requiredPadding);
outer.css('padding', '0 ' + requiredPadding + 'px').css('width','auto');
}
$(document).ready(function(){
// fire on page load
centreThatDiv();
});
$(window).resize(function(){
// fire on window resize
centreThatDiv();
});
HTML:
<div class="outer">
<div class="inner">Centre me!</div>
</div>
CSS:
.outer{ width:80%; height:300px; margin:10%; background: tomato; }
.inner{ width:60px; height:60px; background:white; }
Furthered on from why I disagree with this approach - JavaScript shouldn't be used to lay things out. Sure - it can be, if it really needs to be used; but for something as simple as centring an element, it's not necessary at all. Browsers handle resizing CSS elements themselves, so by using JS you introduce more headaches for yourself further down the line.
Here's a couple of examples of how you can achieve this in CSS only:
text-align:center & display:inline-block https://jsfiddle.net/0uxx2ujg/1/
position:absolute & left:50% https://jsfiddle.net/0uxx2ujg/2/ (this can be used for vertically centring too which is trickier than horizontal)
You can create the new CSS class to adjust for elements size on $window.onresize = function () {
//add your code
};

Image animate down javascript (no jQuery)

I know how to fix the animation that goes down only when the image is showing up in the window with jQuery, but now I want to do that with JavaScript. Struggling with that. The image must be fluently go down (+50px for 1.6 seconds). Have googling around, but most of them are done with jQuery I suggest and that is not what I want. Furtermore the animation should start when the scrollTop is between 600px and 800px.
function scrollFunction() {
var animate = document.getElementById("picture");
var position = 0;
var top = 0;
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
if(scrollTop > 600 && scrollTop < 800){
position++;
animate.style.top = position + "50px";
} else {
stop();
}
}
function stop() {
clearTimeout(animate);
}
#picture {
width: 100%;
height: auto;
top: -5px;
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
margin-bottom: 20px;
}
<div class="col-sm-12 col-xs-12">
<h1 class="responsive-h1">Mi<span class="logo-orange"> Pad2</span></h1>
<p class="edition-title above-text-black">Black Edition</p>
<img src="Img/picture.jpg" id="picture"/>
</div>
jsFiddle : https://jsfiddle.net/n1q3fy8w/
Javascript
var imgSlide = document.getElementById('slidedown-image');
var slideDown = setInterval(function() {
var topVal = parseInt(window.getComputedStyle(imgSlide).top, 10);
imgSlide.style.top = (topVal + 1) + "px";
}, 15);
setTimeout(function( ) { clearInterval( slideDown ); }, 1600);
You get the element first, after that you setup a setInterval which will basically move our img downwards, we then also set a setTimeout which after 1600ms remvoes the slideDown interval and the image stops. Your image however may need position: absolute.
The above answer will only work in Chrome, this however should work in all browswers
jsFiddle : https://jsfiddle.net/n1q3fy8w/1/
javascript
var imgSlide = document.getElementById('slidedown-image');
var slideDown = setInterval(function() {
var topVal = parseInt(imgSlide.style.top, 10);
imgSlide.style.top = (topVal + 1) + "px";
}, 15);
setTimeout(function( ) { clearInterval( slideDown ); }, 1600);
Ok so getComputedStyle only works in chrome, so to get this to work on all other browsers, you have to specifically set the css property on the element and not via CSS.
When you use javascript to access an element and change its style like so element.style.bottom = '150px' the .style gets you all of the css values for your inline styles on that element, so any css changes on an element that is done via a .css/.less file you can't access via javascript.
So all the above code does is we set a top: 0 on the element itself and in our code we use imageSlide.style.top instead of chrome's window.getComputedStyle
Have you considered using a CSS transition? if you are changing the value of top you should be able to add transition: top 1.6s in your css (to picture). (Then the vendor prefixed versions when you get it working)

How do I script such that my panoramic image can be panned left and right up to its edges?

Say my image (panoramic) is 10,000 pixels long, but I want to be able to view only 1000 pixels wide at a time, and in order to view more of it, I can just hover my mouse either left or right, and then the image will move accordingly please? If possible, a simple script on HTML? (I'm not sure how to use Javascript or CSS, but if it needs to come down to that, do guide me step by step?
Thank you.
Here is a simple JQuery which you can use to scroll the whole page when hovering over either the left or right;
Example - https://jsfiddle.net/38da9pca/
Need any help implementing it just leave a comment and I will try and help you.
$(function() {
$('#right').on('mouseenter', rscroll);
$('#left').on('mouseenter', lscroll);
$('#right, #left').on('mouseleave', function() {
$('body').stop();
});
function rscroll() {
$('body').animate({
scrollLeft: '+=25'
}, 10, rscroll);
}
function lscroll() {
$('body').animate({
scrollLeft: '-=25'
}, 10, lscroll);
}
});
Edit (Scroll Image Only)
Example - https://jsfiddle.net/38da9pca/1/
I have change it so the lscroll and the rscroll will effect the id of image instead of the body and change it from scrollLeft to left, and that way it will move the images scroll. Dont forgot to change the $('body').stop(); to $('#bg').stop(); or it will never stop scrolling
$(function() {
$('#right').on('mouseenter', rscroll);
$('#left').on('mouseenter', lscroll);
$('#right, #left').on('mouseleave', function() {
$('#bg').stop();
});
function rscroll() {
$('#bg').animate({
left: '-=25'
}, 10, rscroll);
}
function lscroll() {
$('#bg').animate({
left: '+=25'
}, 10, lscroll);
}
});
Here's one. It's using jquery (javascript library). You would have to add it in order to make it work.
Example:
http://www.gayadesign.com/scripts/jqueryphotonav/
Tutorial:
https://blog.gaya.ninja/articles/jquery-convertion-panoramic-photoviewer-in-javascript/
Something like this?
var imgView = document.querySelectorAll('.img-view')[0];
var img = imgView.querySelectorAll('img')[0];
imgView.onmousemove = function(e) {
var x = e.clientX;
var px = ((x / this.offsetWidth) * 100);
var ix = ((px / 100) * img.offsetWidth);
img.style.left = '-' + (ix - this.offsetWidth) + 'px';
}
.img-view {
width: 256px;
height: 160px;
overflow: hidden;
position: relative;
border: 1px solid #ddd;
}
.img-view img {
height: 100%;
position: relative;
top: 0;
left: 0;
}
<div class="img-view">
<img src="http://panoramalove.com/wp-content/uploads/2013/01/nighttime-panoramic-view-of-hong-kong-island-from-the-avenue-of-stars-in-tsim-sha-tsui.jpg">
</div>

Refresh a page with new div grid

I'm trying to make a grid of divs that, when mouseentered change color. Then, when the a button is clicked and new number is entered to then generate a new grid with a side length of that many divs. I'm new to javascript and jQuery and can't figure out why my code won't generate the divs.
here's my script
$('.block').mouseenter(function () {
$(this).css('background-color', 'black');
});
function newGrid(x) {
for (i = 0; i > x * x; i++) {
$('.container').append('<div class="block"></div>');
}
$('.block').height(960 / );
$('.block').width(960 / );
}
function clearContainer() {
$('.block').remove();
}
function askGrid() {
var num = prompt("enter box length");
clearContainer();
newGrid(num);
}
function firstGrid() {
newGrid(16);
$('#reset').click(function () {
askGrid();
});
}
$(document).ready(firstGrid);
here's my css
.container {
margin: 30px auto 0px auto;
height: 960px;
width: 960px;
border: 1px solid black;
}
.block {
border:0px;
margin:0px;
padding:0px;
float:left;
background-color: yellow;
}
#reset {
display:block;
padding:5px 20px;
margin:0 auto;
}
html has a css reset and in the body i have a button with id="reset" and a div with class="container"
thanks!
Several problems:
The slash when setting height and width is wrong (either is 960 divided by something or just 960)
The for loop is wrong: it should be
for (i = 0; i < x * x; i++)
And the css thing is not going to apply since there are no .block elements when executed. You should probably move it into newGrid
You have a bug here for (i = 0; i > x * x; i++) it should be i < x.
And im not sure what this is
$('.block').height(960 / );
$('.block').width(960 / );
you can set the height and width respectively in the css
Also you need to this for the mouseenter event to work
$('.container').on('mouseenter','.block',function () {
$(this).css('background-color', 'black');
});
Since the items added are dynamic.
Welcome to jquery, a world of excitement and pain!
This code
$('.block').mouseenter(function () {
$(this).css('background-color', 'black');
});
binds the hover function to all existing .block elements on the page when it is run. It's at the top of your script so it'll execute once, binding this property to all .block elements when the page loads, but not to .block elements created after. To fix this add it inside your "newGrid" function so it rebinds each new element as they are created.
In your loop, you want for (i = 1; i < x * x; i++), starting index from 1 rather than 0, or else you'll have an off by 1 error and create an extra box.
To set the proper heights of .block, you want to divide your .container's dimentions by x, the size of block:
$('.block').height(960 / x);
$('.block').width(960 / x);
The following are general programming tips:
As a good practice, functions should have a specific job and only do that job. I moved the clearContainer call to inside newGrid, because it should be the function that builds the new grid that clears the old one, not the one called askGrid. askGrid should do as it is named, and only ask for your new grid dimension.
You should do a validation on the number received through askGrid. If the user types something that isn't a number, or a negative number, or 0, you shouldn't start making boxes or newGrid will break. I added a loop to keep asking for a size until a proper dimension is provided, but you can chose your behaviour.
I changed the variable "x" to "block_length" since variables should be given names indicative of that they mean, so that there aren't a bunch of mysterious variables all over the place called x, y, z that you can't tell what they mean from a glance.
Demo in this fiddle!

Scroll event background change

I am trying to add a scroll event which will change the background of a div which also acts as the window background (it has 100% width and height). This is as far as I get. I am not so good at jquery. I have seen tutorials with click event listeners. but applying the same concept , like, returning scroll event as false, gets me nowhere. also I saw a tutorial on SO where the person suggest use of array. but I get pretty confused using arrays (mostly due to syntax).
I know about plugins like waypoints.js and skrollr.js which can be used but I need to change around 50-60 (for the illusion of a video being played when scrolled) ... but it wont be feasible.
here is the code im using:-
*
{
border: 2px solid black;
}
#frame
{
background: url('1.jpg') no-repeat;
height: 1000px;
width: 100%;
}
</style>
<script>
$(function(){
for ( i=0; i = $.scrolltop; i++)
{
$("#frame").attr('src', ''+i+'.jpg');
}
});
</script>
<body>
<div id="frame"></div>
</body>
Inside your for loop, you are setting the src attribute of #frame but it is a div not an img.
So, instead of this:
$("#frame").attr('src', ''+i+'.jpg');
Try this:
$("#frame").css('background-image', 'url(' + i + '.jpg)');
To bind a scroll event to a target element with jQuery:
$('#target').scroll(function() {
//do stuff here
});
To bind a scroll event to the window with jQuery:
$(window).scroll(function () {
//do stuff here
});
Here is the documentation for jQuery .scroll().
UPDATE:
If I understand right, here is a working demo on jsFiddle of what you want to achieve.
CSS:
html, body {
min-height: 1200px; /* for testing the scroll bar */
}
div#frame {
display: block;
position: fixed; /* Set this to fixed to lock that element on the position */
width: 300px;
height: 300px;
z-index: -1; /* Keep the bg frame at the bottom of other elements. */
}
Javascript:
$(document).ready(function() {
switchImage();
});
$(window).scroll(function () {
switchImage();
});
//using images from dummyimages.com for demonstration (300px by 300px)
var images = ["http://dummyimage.com/300x300/000000/fff",
"http://dummyimage.com/300x300/ffcc00/000",
"http://dummyimage.com/300x300/ff0000/000",
"http://dummyimage.com/300x300/ff00cc/000",
"http://dummyimage.com/300x300/ccff00/000"
];
//Gets a valid index from the image array using the scroll-y value as a factor.
function switchImage()
{
var sTop = $(window).scrollTop();
var index = sTop > 0 ? $(document).height() / sTop : 0;
index = Math.round(index) % images.length;
//console.log(index);
$("#frame").css('background-image', 'url(' + images[index] + ')');
}
HTML:
<div id="frame"></div>
Further Suggestions:
I suggest you change the background-image of the body, instead of the div. But, if you have to use a div for this; then you better add a resize event-istener to the window and set/update the height of that div with every resize. The reason is; height:100% does not work as expected in any browser.
I've done this before myself and if I were you I wouldn't use the image as a background, instead use a normal "img" tag prepend it to the top of your page use some css to ensure it stays in the back under all of the other elements. This way you could manipulate the size of the image to fit screen width better. I ran into a lot of issues trying to get the background to size correctly.
Html markup:
<body>
<img src="1.jpg" id="img" />
</body>
Script code:
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200) {
// function goes here
$('img').attr('src', ++count +'.jpg');
}
});
});
I'm not totally sure if this is what you're trying to do but basically, when the window is scrolled, you assign the value of the distance to the top of the page, then you can run an if statement to see if you are a certain point. After that just simply change run the function you would like to run.
If you want to supply a range you want the image to change from do something like this, so what will happen is this will allow you to run a function only between the specificied range between 200 and 400 which is the distance from the top of the page.
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200 && topPage < 400) {
// function goes here
$('#img').attr('src', ++count +'.jpg');
}
});
});

Categories

Resources