Audio on scroll in a DIV - javascript

I want to enable audio in a selected area of the page. If the user scrolls out this element, audio will stop.
I found this solution but the problem is that pixels values are different in order the resolution of the window, monitor, kind of browser etc.
var playing = false;
var audioElm = $('#soundTour').get(0);
$(window).scroll(function() {
var pageScroll = $(window).scrollTop();
if(!playing && pageScroll > 500 && pageScroll < 3000){
audioElm.play();
playing = true;
}else if(pageScroll > 3000 || pageScroll < 500){
audioElm.pause();
playing = false;
}
});
For that I'd like to find a solution in a DIV.
My one page is like this:
https://alvarotrigo.com/fullPage/examples/navigationV.html#firstPage
and I want that the background sound, for example, will autoplay during the first and second page, and will stop when the user join the third page.
Any help?

In code below sound starts playing when 30% of the third block is visible.
<html>
<head>
<meta charset="utf-8" />
<style>
body { margin: 0; padding: 0; }
</style>
</head>
<body>
<audio src="/sound.wav"></audio>
<div style="height: 100%; background: #ff5555">first page</div>
<div style="height: 100%; background: #55ff55">second page</div>
<div id="d3" style="height: 100%; background: #5555ff">third page</div>
<script>
const el = document.querySelector("audio");
let playing = false;
window.addEventListener('scroll', (e) => {
const scroll = e.target.body.scrollTop;
const rect = document.getElementById("d3").getBoundingClientRect();
const top = rect.top;
if (!playing && top > rect.height / 3) {
el.play();
playing = true;
} else if (top < rect.height / 3) {
el.pause();
playing = false;
}
});
</script>
</body>
</html>
Update after comments:
<html>
<head>
<meta charset="utf-8" />
<style>
body { margin: 0; padding: 0; }
</style>
</head>
<body>
<div id="d1" style="height: 100%; background: #ff5555">first page</div>
<div id="d2" style="height: 100%; background: #55ff55">second page</div>
<div id="d3" style="height: 100%; background: #5555ff">third page</div>
<script>
const soundfiles = ["sound.wav", "sound2.wav", "sound.wav"];
const divIds = ["d1", "d2", "d3"];
const els = soundfiles.map((filename, index) => {
const el = document.createElement("audio");
el.src = "/" + filename;
document.body.appendChild(el);
return el;
})
const playing = new Array(divIds.length).fill(false);
window.addEventListener('scroll', (e) => {
const scroll = e.target.body.scrollTop;
const rects = divIds.map(id => document.getElementById(id).getBoundingClientRect());
const tops = rects.map(rect => rect.top);
tops.forEach((top, ind) => {
if (!playing[ind] && top <= rects[ind].height * 2 / 3 && top > - rects[ind].height * 1 / 3) {
els[ind].play();
playing[ind] = true;
} else if (playing[ind] && (top > rects[ind].height * 2 / 3 || top < -rects[ind].height * 1 / 3)) {
els[ind].pause();
playing[ind] = false;
}
});
});
</script>
</body>
</html>

Related

How can I get the size of the grid to stay the same regardless of the number of divs inside (the new number i enter)?

I am working on The Odin Project and I am on the etch-a-sketch section. I believe I have every part working except resizing the grid when a new number is entered. Any help would be greatly appreciated.
const container = document.getElementById("container");
const button = document.querySelector("input");
button.addEventListener('click', ()=> {
numOfSquares();
})
function numOfSquares() {
if (button.value === "number of squares") {
let newNumPerRow = prompt("how many squares per side would you like?", "");
let parse = parseInt(newNumPerRow);
makeRows(parse);
}
}
function hoverColor() {
let items = document.querySelectorAll('.gridItems');
items.forEach(item => {
item.addEventListener('mouseover', () => {
item.style.backgroundColor = 'orange';
});
});
}
function clearGrid() {
const gridArray = Array.from(container.childNodes);
gridArray.forEach(element => {
container.removeChild(element);
})
}
function makeRows (numberPerRow) {
clearGrid();
const total = (numberPerRow * numberPerRow) + numberPerRow;
const box = numberPerRow + 1;
for (i=0; i < total; i++) {
const div = document.createElement('div');
container.appendChild(div).className = "gridItems";
if (i % box === 0) {
div.style.cssText = "border: 0; height: 0; width: 100%";
} else {
div.style.cssText = "border: 1px solid black; height: 25px; width: 25px";
}
}
hoverColor();
}
makeRows(16);
I have tried to change the inline div style in javascript portion underneath the makeRows function, but nothing seems to work. Unless I completely miss something.
CSS
* {
box-sizing: border-box;
}
#container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch-A-Sketch Project</title>
<link rel="stylesheet" href="style.css">
<script src="index.js" defer></script>
</head>
<body>
<input type="button" value="number of squares">
<div id="container">
</div>
</body>
</html>
I'm not familiar with the project exactly, but taking a look at your js, it looks like you're hard-coding the width value for the elements. Something like this may be helpful if you need to use flex:
function makeRows(numberPerRow) {
clearGrid();
const total = numberPerRow * numberPerRow + numberPerRow;
const box = numberPerRow + 1;
for (i = 0; i < total; i++) {
const div = document.createElement("div");
container.appendChild(div).className = "gridItems";
if (i % box === 0) {
div.style.cssText = "border: 0; height: 0; width: 100%";
} else {
//dynamically resize?
div.style.cssText = `border: 1px solid black; height: ${
1000 / numberPerRow
}px; width: ${1000 / numberPerRow}px`;
//dynamically resize?
}
}
hoverColor();
}
Since you are making a grid though, it may be more helpful to use grid layout rather than flex.
https://developer.mozilla.org/en-US/docs/Web/CSS/grid
https://www.w3schools.com/css/css_grid.asp
I'm giving you a solution using display: grid as this is the preferred method to use when creating a grid (it's in the name).
I left the HTML the exact same.
const container = document.getElementById("container");
const button = document.querySelector("input");
button.addEventListener('click', ()=> {
numOfSquares();
})
function numOfSquares() {
if (button.value === "number of squares") {
let newNumPerRow = prompt("how many squares per side would you like?", "");
let parse = parseInt(newNumPerRow);
makeRows(parse);
}
}
function hoverColor() {
let items = document.querySelectorAll('.gridItems');
items.forEach(item => {
item.addEventListener('mouseover', () => {
item.style.backgroundColor = 'orange';
});
});
}
function clearGrid() {
const gridArray = Array.from(container.childNodes);
gridArray.forEach(element => {
container.removeChild(element);
})
}
function makeRows (numberPerRow) {
clearGrid();
//Set the grid template columns straight from JavaScript
container.style.gridTemplateColumns = `repeat(${numberPerRow}, 1fr)`;
//Resolved an issue here that was adding an extra row
const total = numberPerRow * numberPerRow;
//Idk what the point of box was so I removed it for the sake of the answer
for (i = 0; i < total; i++) {
const div = document.createElement('div');
container.appendChild(div).className = "gridItems";
//Moved the gridItem styling to CSS
}
hoverColor();
}
makeRows(16);
* {
box-sizing: border-box;
}
#container {
display: grid;
width: 100%; /* Set whichever width you want here */
aspect-ratio: 1/1;
}
.gridItems {
border: 1px solid black;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch-A-Sketch Project</title>
<link rel="stylesheet" href="style.css">
<script src="index.js" defer></script>
</head>
<body>
<input type="button" value="number of squares">
<div id="container">
</div>
</body>
</html>
Add this at the top of you js and specify the size of your grid in px. You can add it to makeRows as a variant:
const preservedWidth = 600;
Also add boxWidth to makeRows to calculate the width of your grid element:
const boxWidth = preservedWidth / numberPerRow;
Change this:
div.style.cssText = "border: 1px solid black; height: 25px; width: 25px";
to:
div.style.cssText = `border: 1px solid black; height: ${boxWidth}; width: ${boxWidth}`;
This is the whole JS code:
const container = document.getElementById("container");
const button = document.querySelector("input");
const preservedWidth = 300;
button.addEventListener('click', ()=> {
numOfSquares();
})
function numOfSquares() {
if (button.value === "number of squares") {
let newNumPerRow = prompt("how many squares per side would you like?", "");
let parse = parseInt(newNumPerRow);
makeRows(parse);
}
}
function hoverColor() {
let items = document.querySelectorAll('.gridItems');
items.forEach(item => {
item.addEventListener('mouseover', () => {
item.style.backgroundColor = 'orange';
});
});
}
function clearGrid() {
const gridArray = Array.from(container.childNodes);
gridArray.forEach(element => {
container.removeChild(element);
})
}
function makeRows (numberPerRow) {
clearGrid();
const total = (numberPerRow * numberPerRow) + numberPerRow;
const box = numberPerRow + 1;
const boxWidth = preservedWidth / numberPerRow;
for (i=0; i < total; i++) {
const div = document.createElement('div');
container.appendChild(div).className = "gridItems";
if (i % box === 0) {
div.style.cssText = "border: 0; height: 0; width: 100%";
} else {
div.style.cssText = `border: 1px solid black; height: ${boxWidth}; width: ${boxWidth}`;
}
}
hoverColor();
}
makeRows(16);

Trying to figure out why clock is not resetting and top popped balloons not displaying in game

This game is designed to inflate a balloon until it pops. The timer is supposed to countdown until it reaches zero. Once it reaches zero it is supposed to display under "top popped" the high score of how many balloons popped. What is happening is time keeps decrementing into negative numbers instead of stopping at zero. Also, nothing displaying under top popped.
I am receiving the following messages in the console log which I don't now how to interpret or deconstruct. I am very new to javascript.
enter image description here
Here is the JS and HTML:
let startButton = document.getElementById('start-button')
let inflateButton = document.getElementById('inflate-button')
// we care about this data
let clickCount = 0
let height = 120
let width = 100
let inflationRate = 20
let maxsize = 300
let highestPopCount = 0
let currentPopCount = 0
let gameLength = 5000
let ClockId = 0
let timeRemaining = 0
function startGame() {
startButton.setAttribute("disabled", "true")
inflateButton.removeAttribute ("disabled")
startClock()
setTimeout(stopGame, gameLength)
}
function startClock(){
timeRemaining = gameLength
drawClock()
ClockId = setInterval(drawClock, 1000)
}
function stopClock(ClockId){
clearInterval(ClockId)
}
function drawClock(){
let countdownElem = document.getElementById("countdown")
countdownElem.innerText = (timeRemaining / 1000).toString()
timeRemaining -= 1000
}
function inflate(){
clickCount ++
height += inflationRate
width += inflationRate
if(height >= maxsize){
console.log("pop the balloon")
currentPopCount ++
height = 0
width = 0
}
draw()
}
function draw(){
let balloonElement = document.getElementById("balloon")
let clickCountElem = document.getElementById("click-count")
let popCountElem = document.getElementById('pop-count')
let highPopCountElem = document.getElementById('high-pop-count')
balloonElement.style.height = height + "px"
balloonElement.style.width = width + "px"
clickCountElem.innerText = clickCount.toString()
popCountElem.innerText = currentPopCount.toString()
highPopCount,innerText = highestPopCount.toString()
}
function stopGame(){
console.log ("the game is over")
inflateButton.setAttribute("disabled", "true")
startButton.removeAttribute ("disabled")
clickCount = 0
height = 120
width = 100
if(highestPopCount > currentPopCount){
}
currentPopCount = 0
stopClock()
draw()
}
body{
background-color: wheat;
}
.balloon {
height: 128px;
width: 100px;
background-color: blue
;
border-radius: 50%
;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Balloon Pop</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<button id="start-button" onclick="startGame()" >START GAME</button>
</div>
<button id="inflate-button" onclick="inflate()" disabled="true">Inflate <span id="click-count"> </span></button>
<div>
<span>Balloons Popped:</span>
<span id="pop-count"></span>
</div>
<div>
<span>Top Popped:</span>
<span id="high-pop-count"></span>
</div>
<div>
<span>Time Remaining:</span>
<span id="countdown">0</span>
</div>
<div id="balloon" class="balloon" ></div>
<script src="main.js"></script>
</body>
</html>
Fix the scoping of the ClockId variable.
In your stopClock function, you're asking for an argument of ClockId but you're never passing it along, instead you're expecting the global ClockId to be used. The more specific scoped variable (the argument) takes over that variable name.
function stopClock(ClockId){
clearInterval(ClockId)
}
/// Should be -
function stopClock() {
clearInterval(ClockId)
}
/// Note, I don't like using globals like you have here, but I get the low discipline on learning projects.
I also added the code needed to assign the highest pop count.
if (highestPopCount < currentPopCount) {
highestPopCount = currentPopCount;
}
let startButton = document.getElementById('start-button')
let inflateButton = document.getElementById('inflate-button')
// we care about this data
let clickCount = 0
let height = 120
let width = 100
let inflationRate = 20
let maxsize = 300
let highestPopCount = 0
let currentPopCount = 0
let gameLength = 5000
var ClockId = 0
var timeRemaining = 0
function startGame() {
startButton.setAttribute("disabled", "true")
inflateButton.removeAttribute("disabled")
startClock()
setTimeout(stopGame, gameLength)
}
function startClock() {
timeRemaining = gameLength
drawClock()
ClockId = setInterval(drawClock, 1000)
}
function stopClock() {
clearInterval(ClockId)
}
function drawClock() {
let countdownElem = document.getElementById("countdown")
countdownElem.innerText = (timeRemaining / 1000).toString()
timeRemaining -= 1000
}
function inflate() {
clickCount++
height += inflationRate
width += inflationRate
if (height >= maxsize) {
console.log("pop the balloon")
currentPopCount++
height = 0
width = 0
}
draw()
}
function draw() {
let balloonElement = document.getElementById("balloon")
let clickCountElem = document.getElementById("click-count")
let popCountElem = document.getElementById('pop-count')
let highPopCountElem = document.getElementById('high-pop-count')
balloonElement.style.height = height + "px"
balloonElement.style.width = width + "px"
clickCountElem.innerText = clickCount.toString()
popCountElem.innerText = currentPopCount.toString()
highPopCountElem.innerText = highestPopCount.toString()
}
function stopGame() {
console.log("the game is over")
inflateButton.setAttribute("disabled", "true")
startButton.removeAttribute("disabled")
clickCount = 0
height = 120
width = 100
if (highestPopCount < currentPopCount) {
highestPopCount = currentPopCount;
}
currentPopCount = 0
stopClock()
draw()
}
body {
background-color: wheat;
}
.balloon {
height: 128px;
width: 100px;
background-color: blue;
border-radius: 50%;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Balloon Pop</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<button id="start-button" onclick="startGame()">START GAME</button>
</div>
<button id="inflate-button" onclick="inflate()" disabled="true">Inflate <span id="click-count"> </span></button>
<div>
<span>Balloons Popped:</span>
<span id="pop-count"></span>
</div>
<div>
<span>Top Popped:</span>
<span id="high-pop-count"></span>
</div>
<div>
<span>Time Remaining:</span>
<span id="countdown">0</span>
</div>
<div id="balloon" class="balloon"></div>
<script src="main.js"></script>
</body>
</html>

How to swipe loaded epub left and right using javascript

Good day all, I want to apply swipe to my loaded epub. I used javascript to load the epub into a div, I want to be able to do swipe left and swipe right on the div.
I got a jquery script to do that, but the challenge is that, it doesn't swipe on the div, it swipes when I do mouse swipe left or right on other controls on the page, such as input control and select control.
But on the main div with epub, it doesn't swipe or the swipe doesn't get called.
Thanks for your help
Edit: After checking the developer tools side, I noticed that after the epub is loaded in the area div, it is loaded into an iframe, i've been trying to target the iframe, for touchmove event, but not yet successful.
Below is the developer inspect code, thanks.
<div id="area" class="swipe-detector">
<iframe id="epubjs-iframe:2dc3e713-d94a-4f98-a8d2-0ec974ed045b"
scrolling="no" height="100%" width="100%" style="border: none;
visibility: visible;">
#document
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
style="transform: translate(0px, 0px); overflow: hidden; width: auto;
height: 609px; column-fill: auto; column-width: 361px; column-gap:
44px;">
<head>
<base href="OEBPS/table-of-contents.html">
<title>Table Of Contents -- The Problems of Philosophy</title>
<meta http-equiv="Content-Type"
content="application/xhtml+xml; charset=utf-8">
<meta name="EPB-UUID" content="">
<link rel="stylesheet" href="blob:null/64628d08-cd14-43f0-
93cf-4589c1eb1f9b" type="text/css">
</head>
<body style="margin: 0px;">
...
</body>
</html>
</iframe>
</div>
Please check my original code below:
<body class="swipe-detector">
<div id="reader">
<input type="file" id="bookChooser">
<select id="toc"></select>
<div id="area" class="swipe-detector"></div>
<button id="prev" type="button"><</button>
<button id="next" type="button">></button>
</div>
<script>
(function($) {
$.fn.swipeDetector = function(options) {
// States: 0 - no swipe, 1 - swipe started, 2 - swipe released
var swipeState = 0;
// Coordinates when swipe started
var startX = 0;
var startY = 0;
// Distance of swipe
var pixelOffsetX = 0;
var pixelOffsetY = 0;
// Target element which should detect swipes.
var swipeTarget = this;
var defaultSettings = {
// Amount of pixels, when swipe don't count.
swipeThreshold: 70,
// Flag that indicates that plugin should react only on touch events.
// Not on mouse events too.
useOnlyTouch: false
};
// Initializer
(function init() {
options = $.extend(defaultSettings, options);
// Support touch and mouse as well.
swipeTarget.on("mousedown touchstart", swipeStart);
$("html").on("mouseup touchend", swipeEnd);
$("html").on("mousemove touchmove", swiping);
})();
function swipeStart(event) {
if (options.useOnlyTouch && !event.originalEvent.touches) return;
if (event.originalEvent.touches) event = event.originalEvent.touches[0];
if (swipeState === 0) {
swipeState = 1;
startX = event.clientX;
startY = event.clientY;
}
}
function swipeEnd(event) {
if (swipeState === 2) {
swipeState = 0;
if (
Math.abs(pixelOffsetX) > Math.abs(pixelOffsetY) &&
Math.abs(pixelOffsetX) > options.swipeThreshold
) {
// Horizontal Swipe
if (pixelOffsetX < 0) {
swipeTarget.trigger($.Event("swipeLeft.sd"));
console.log("Left");
} else {
swipeTarget.trigger($.Event("swipeRight.sd"));
console.log("Right");
}
} else if (Math.abs(pixelOffsetY) > options.swipeThreshold) {
// Vertical swipe
if (pixelOffsetY < 0) {
swipeTarget.trigger($.Event("swipeUp.sd"));
console.log("Up");
} else {
swipeTarget.trigger($.Event("swipeDown.sd"));
console.log("Down");
}
}
}
}
function swiping(event) {
// If swipe don't occuring, do nothing.
if (swipeState !== 1) return;
if (event.originalEvent.touches) {
event = event.originalEvent.touches[0];
}
var swipeOffsetX = event.clientX - startX;
var swipeOffsetY = event.clientY - startY;
if (
Math.abs(swipeOffsetX) > options.swipeThreshold ||
Math.abs(swipeOffsetY) > options.swipeThreshold
) {
swipeState = 2;
pixelOffsetX = swipeOffsetX;
pixelOffsetY = swipeOffsetY;
}
}
return swipeTarget; // Return element available for chaining.
};
})(jQuery);
// Showcase
$("document").ready(function() {
$(".swipe-detector")
.swipeDetector()
.on("swipeLeft.sd swipeRight.sd swipeUp.sd swipeDown.sd", function(event) {
if (event.type === "swipeLeft") {
console.log("Swipe Left");
} else if (event.type === "swipeRight") {
console.log("Swipe Right");
} else if (event.type === "swipeUp") {
console.log("Swipe Up");
} else if (event.type === "swipeDown") {
console.log("Swipe Down");
}
});
});
</script>
</body>
So the hack is to place a div over the area div, then swipe over that to perform the previous and next moves.
The solution is at this link:
How to cover a div with another div as overlay

JS: Slideshow inaccurate result

Hi I write this simple javascript slideshow cause I want to write my own slideshow in javascript. It automatically change the images by a set time interval. But when I try to click the backward and forward function the result is not accurate or the images are in order.
var images = ["http://i1214.photobucket.com/albums/cc487/myelstery/1.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/2.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/3.jpg"];
var i = 0;
var count = images.length;
function slidingImages()
{
i = i % count;
document.banner.src = images[i];
i++;
}
function forward()
{
i = (i + 1) % count;
document.banner.src=images[i];
}
function backward()
{
if (i <= 0)
{
i = count - 1;
}
else
{
i--;
}
document.banner.src=images[i];
}
window.onload = function()
{
slidingImages(),setInterval(slidingImages, 3000)
};
<center>
<p>
<img src="images/1.jpg" name="banner" id="name"/>
</p>
<input type="button" value="«prev" onClick="backward()">
<input type="button" value="next»" onClick="forward()">
</center>
What is the solution so my slideshow would be accurate?
This will pause the automatic behavior when the mouse is within the red rectangle and continue in auto mode once the mouse is out of the red rectangle. The buttons of course work as expected.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
fieldset { width: -moz-fit-content; width: -webkit-fit-content; width: fit-content; border: 1px solid red; }
</style>
</head>
<body>
<section>
<p>
<img src="images/1.jpg" name="banner" id="name"/>
</p>
<fieldset id="control">
<input id="prev" type="button" value="◄">
<input id="next" type="button" value="►">
</fieldset>
</section>
<script>
var images = ["http://i1214.photobucket.com/albums/cc487/myelstery/1.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/2.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/3.jpg"];
var i = -1;
var count = images.length;
var prev = document.getElementById('prev');
var next = document.getElementById('next');
var control = document.getElementById('control');
var autoSlide;
window.onload = auto;
function auto() {
autoSlide = setInterval(fwd, 3000) };
function pause() {
clearInterval(autoSlide);
}
function fwd() {
if (i >= 0 && i < 2)
{
i += 1;
}
else
{
i = 0;
}
document.banner.src=images[i];
}
function rev() {
if (i > 0 && i <= 2)
{
i -= 1;
}
else
{
i = 2;
}
document.banner.src=images[i];
}
prev.addEventListener('click', function() {
rev();
}, false);
next.addEventListener('click', function() {
fwd();
}, false);
control.addEventListener('mouseover', function() {
pause();
}, false);
control.addEventListener('mouseout', function() {
auto();
}, false);
</script>
</body>
</html>

(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;

Categories

Resources