javascript, slide div down on button click? - javascript

i am trying to get a div to slide down about 200px down a page using javascript when the user clicks another div which acts as a close button.
can someone please show me how i would do this?
<script>
$('.chat_close').click(function(e){
$('.chat_box').slideDown();
});
</script>

Someone already asked the same question a while ago. Avinash replied:
var minheight = 20;
var maxheight = 100;
var time = 1000;
var timer = null;
var toggled = false;
window.onload = function() {
var controler = document.getElementById('slide');
var slider = document.getElementById('slider');
slider.style.height = minheight + 'px'; //not so imp,just for my example
controler.onclick = function() {
clearInterval(timer);
var instanceheight = parseInt(slider.style.height); // Current height
var init = (new Date()).getTime(); //start time
var height = (toggled = !toggled) ? maxheight: minheight; //if toggled
var disp = height - parseInt(slider.style.height);
timer = setInterval(function() {
var instance = (new Date()).getTime() - init; //animating time
if(instance <= time ) { //0 -> time seconds
var pos = instanceheight + Math.floor(disp * instance / time);
slider.style.height = pos + 'px';
}else {
slider.style.height = height + 'px'; //safety side ^^
clearInterval(timer);
}
},1);
};
};
You can see it here at this URL:
http://jsbin.com/azewi5

Use animate
Also, use .on
<script type="text/javascript">
$('.chat_close').on('click', function(e){
$('.chat_box').animate({"top": "200px");
});
</script>
HTML:
<div class="chat_close">
</div>

Related

How to call function every time div reaches max-height?

I want to call a function only once every time the div #blinds reach their max-height at 430px, how can I do this?
My Codepen: https://codepen.io/cocotx/pen/YzGBpVJ
window.addEventListener('mousemove', function(event) {
var blinds = document.getElementById("blinds");
blinds.style.height = event.clientY + 'px';
});
One polling way is adding the code below in your js if there are other behaviours changing the size of the element. Simply change 400 to the value you want.
var blinds = document.getElementById("blinds");
setInterval(() => {
let rect = blinds.getBoundingClientRect();
if (rect.height > 400)
console.log(" reach 400");
}, 100);
window.addEventListener('mousemove', function(event) {
var blinds = document.getElementById("blinds");
blinds.style.height = event.clientY + 'px';
// i added here the condition
if(blinds.offsetHeight > 430 /*the value you want*/){
//call your function
}
});
Notice that this doesn't work if you use blinds.style.height instead of blinds.offsetHeight, there's a difference between using these but i im still trying to figure it out.
I would suggest to clean your code:
window.addEventListener('mousemove',handler);
function handler(event){
...
if(blinds.offsetHeight >430){
//call your function
...
//and maybe remove the listener
window.removeEventListener('mousemove',handler);
}
};
EDIT: try this code
function hasReachedMax(){
var styles = getComputedStyle(blinds);
var borderBottom = styles.borderBottom.split("px")[0]; //this is to get the number of pixels
var borderTop = styles.borderTop.split("px")[0];
var maxH = styles.maxHeight.split("px")[0];
var currentDivSize = blinds.offsetHeight-borderBottom-borderTop;
return maxH == currentDivSize;
};
function resetTrigger(){
//the condition to reset your trigger, for example making the div element at least 5 px smaller than maxHeight
var styles = getComputedStyle(blinds);
var borderBottom = styles.borderBottom.split("px")[0];
var borderTop = styles.borderTop.split("px")[0];
var maxH = styles.maxHeight.split("px")[0];
var currentDivSize = blinds.offsetHeight-borderBottom-borderTop;
return maxH-currentDivSize>5;
};
//this should be part of your main code
var trigger = true;
window.addEventListener('mousemove', function(event) {
var blinds = document.getElementById("blinds");
blinds.style.height = event.clientY + 'px';
if(hasReachedMax()&&trigger){
//call your function
console.log("Im called now");
trigger=false;
}
if(resetTrigger()) trigger=true;
});

How to pause Text Javascript / var textarray?

I am trying to Pause and Resume the javascript by clicking on the page.
I have text scrolling that changes by fading in and out.
The solutions I found online were how to pause marquee's, but I think that solution doesn't apply since my code doesn't use marquee tags.
Also for my text scrolling I'm not showing text, but images.
I was wondering how could I go about pausing and resuming the images by clicking on the page?
<div id="menu">
<button id="start-stop">Start/stop</button>
</div>
<div id="random_text"></div>
</div>
<script type="text/javascript">
$(window).load(function() {
$(window).resize(function() {
var windowHeight = $(window).height();
var containerHeight = $(".container").height();
$(".container").css("top", (windowHeight / 2 - containerHeight * 0.7) + "px");
});
var textarray = [
"<img class=\"tall\" src=\"1.png\" alt=\"1\"></img><span class=\"by\">Example</span>" ,
"<img class=\"wide\" src=\"2.png\" alt=\"2\"></img><span class=\"by\">Example</span>",
"<img class=\"wide\" src=\"3.png\" alt=\"3\"></img><span class=\"by\">Example</span>",
"<img class=\"wide\" src=\"4.png\" alt=\"4\"></img><span class=\"by\">Example</span>",
];
var firstTime = true;
function RndText() {
var rannum = Math.floor(Math.random() * textarray.length);
if (firstTime) {
$('#random_text').fadeIn('fast', function() {
$(this).html(textarray[rannum]).fadeOut('fast');
});
firstTime = false;
}
$('#random_text').fadeOut('fast', function() {
$(this).html(textarray[rannum]).fadeIn('fast');
});
var windowHeight = $(window).height();
var containerHeight = $(".container").height();
// $(".container").css("top", (windowHeight / 2 - containerHeight * 0.7) + "px");
}
$(function() {
// Call the random function when the DOM is ready:
RndText();
});
var inter = setInterval(function() {
intervalRunning = true;
RndText();
}, 3000);
});
$(document).on('click', '#start-stop', function(){
if (intervalRunning) {
intervalRunning = false;
clearInterval(inter);
} else {
inter = setInterval(function() {
intervalRunning = true;
RndText();
}, 3000);
}
})
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
I've created a jsbin to show a basic solution.
Since you are using jQuery, I would change how everything is structured. I would wrap the code in $(document).ready, so that it fires once the DOM is ready.
Create a bool at the outset to track if the interval is running:
var running = false;
Create a handler for the interval to turn on or off as needed:
var handleInterval = function(){
if (running) {
running = false;
clearInterval(intObj);
} else {
intObj = setInterval(function(){
running = true;
RndText();
}, 1500);
}
};
Set a handler for the button:
$(document).on("click", "#pause_me", function(){
handleInterval();
});
Kick the whole thing off with a call to handleInterval:
handleInterval();

Javascript - setInterval for 2 auto slide on the same page

I was trying to create a auto slide for the slider using setInterval. It works like a charm when there's only one slider.
When there are 2 slider, the first slider wont work, and the second slider will slide faster, because there will be 2 setInterval and both are sliding the second slider. Anyway to make sure each setInterval slide their own slider?
var autoSlideTimer = 5;
var autoslide = setInterval(function () {
if (autoSlideTimer == 0) {
var slideMargin = offsetMarginLeft - width;
if (-slideMargin == (width * totalImages)) {
offsetMarginLeft = width;
displayImage = 0;
}
slider.style.marginLeft = (offsetMarginLeft - width) + 'px';
displayImage += 1;
pagination = element.getElementsByTagName('ul')[0];
pagination.innerHTML = paginate;
pagination.getElementsByTagName('li')[displayImage - 1].setAttribute("class", "displayed");
slider = element.getElementsByTagName('div')[0];
offsetMarginLeft = parseInt(slider.style.marginLeft.replace('px', ''));
autoSlideTimer = 5;
} else {
autoSlideTimer--;
}
}, 1000);
thanks
I work it out with another way, although is working but doesnt seems to be the perfect way
var event = new Event('build');
// Listen for the event.
element.addEventListener('build', function (e) {
function timeoutLoop()
{
setTimeout(function(){
if(autoSlideTimer == 0)
{
var slideMargin = offsetMarginLeft - width;
if(-slideMargin == (width * totalImages))
{
offsetMarginLeft = width;
displayImage = 0;
}
slider.style.marginLeft = (offsetMarginLeft - width) + 'px';
displayImage += 1;
pagination = element.getElementsByTagName('ul')[0];
pagination.innerHTML = paginate;
pagination.getElementsByTagName('li')[displayImage - 1].setAttribute("class", "displayed");
offsetMarginLeft = parseInt(slider.style.marginLeft.replace('px', ''));
autoSlideTimer = 5;
}else
{
autoSlideTimer--;
}
timeoutLoop();
},1000);
}
timeoutLoop();
}, false);
// Dispatch the event.
element.dispatchEvent(event);
At first, I used setInterval inside, yet the slider will be overwritten. But setTimeout is ok.

Scroll down animation js

I built a kind of chat in JS and then I wanted that when I got new message the chat automatically scrolled down (with animation...). Everything worked beautifully, but after the animation stopped the user couldn't scroll by himself; the chat automatically scrolled to the end.
So this is the code :
<!-- language:lang-js -->
var height = 1;
window.setInterval(function() {
var elem = document.getElementById('chat');
elem.scrollTop = height;
if (elem.scrollheight < height) {
clearInterval(this);
}
height += 2;
}, 50);
the clearInterval function expects a number. Using that should make it work correctly. You also have many syntax errors.
var intervalReference = window.setInterval(function() {
var elem = document.getElementById('chat');
elem.scrollTop = height;
if (elem.scrollHeight < height) {
clearInterval(intervalReference);
}
height += 2;
}, 50);
you should make a var holding the interval like this :
var height = 1;
var interval = window.setInterval( animate, 50 );
function animate() {
var elem = document.getElementById('chat');
elem.scrollTop = height;
if (elem.scrollHeight < height) {
clearInterval( interval );
}
height += 2;
}
this should work fine

javascript toggle animation issue

I am doing a small javascript animation. this is my code :
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
heading.onclick = function () {
var divHeight = 250;
var speed = 10;
var myInterval = 0;
alert(divHeight);
slide();
function slide() {
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
alert('i am called as slide down')
}
}
function slideUp() {
var anima = document.getElementById('anima');
if (divHeight <= 0) {
divHeight = 0;
anima.style.height = '0px';
clearInterval(myInterval);
} else {
divHeight -= speed;
if (divHeight < 0) divHeight = 0;
anima.style.height = divHeight + 'px';
}
}
function slideDwn() {
var anima = document.getElementById('anima');
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
} else {
divHeight += speed;
anima.style.height = divHeight + 'px';
}
}
}
}
i am using above code for simple animation. i need to get the result 250 on the first click, as well second click i has to get 0 value. but it showing the 250 with unchanged. but i am assigning the value to set '0', once the div height reached to '0'.
what is the issue with my code? any one help me?
Everytime you click on the div the divHeight variable is reset to 250, thus your code never calls slideDwn. Moving the divHeight declaration outside the event handler should do the trick.
Also, your div wont have the correct size when any of the 2 animations end. You're setting the divHeight variable to 250 or 0 correctly, but never actually setting anima.style.height after that.
I've rewritten your code into something simpler and lighter. The main difference here is that we're using a single slide() function here, and that the height of the div in question is stored in a variable beforehand to ensure that the element slides into the correct position.
Note that this is a very simplistic implementation and assumes that the div carries no padding. (The code uses ele.clientHeight and ele.style.height interchangeably, which admittedly, is a pretty bad choice, but is done here to keep the code simple)
var heading = document.getElementsByTagName('h1')[0],
anima = document.getElementById('anima'),
divHeight = anima.clientHeight,
speed = 10,
myInterval = 0,
animating = false;
function slide(speed, goal) {
if(Math.abs(anima.clientHeight - goal) <= speed){
anima.style.height = goal + 'px';
animating = false;
clearInterval(myInterval);
} else if(anima.clientHeight - goal > 0){
anima.style.height = (anima.clientHeight - speed) + 'px';
} else {
anima.style.height = (anima.clientHeight + speed) + 'px';
}
}
heading.onclick = function() {
if(!animating) {
animating = true;
var goal = (anima.clientHeight >= divHeight) ? 0 : divHeight;
myInterval = setInterval(slide, 13, speed, goal);
}
}
See http://www.jsfiddle.net/yijiang/dWJgG/2/ for a simple demo.
I've corrected your code a bit (See working demo)
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
var anima = document.getElementById('anima');
var divHeight = 250;
heading.onclick = function () {
var speed = 10;
var myInterval = 0;
function slideUp() {
divHeight -= speed;
if (divHeight <= 0) {
divHeight = 0;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slideDwn() {
divHeight += speed;
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slide() {
console.log(divHeight )
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
}
}
slide();
}
}​

Categories