(HTML) JavaScript Collapsible Menu Error - javascript

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;

Related

Event handling onclick Body response in every object

There is a pattern game in which the user is supposed to find 1 missed picture from right side while the location is shown on left, then if the user guessed correctly they will go to the next level.
My problem is that, even though I clicked on correct picture, the popup for wrong choice is appearing after the first iteration.
I tried to define body as the initial child but still popup is displaying regardless of correct or wrong choice.
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
var theBody = document.getElementsByTagName("body")[0];
function generateFaces() {
for (var i = 0; i < numberOfFaces; i++) {
var createImg = document.createElement("IMG");
var randPositionTop = Math.floor(Math.random() * 400);
var randPositionleft = Math.floor(Math.random() * 400);
createImg.setAttribute("src", "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png");
createImg.style.top = randPositionTop + "px";
createImg.style.left = randPositionleft + "px";
theLeftSide.appendChild(createImg);
}
var leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);
theLeftSide.lastChild.onclick =
function nextLevel(event) {
event.stopPropagation;
numberOfFaces += 5;
alert("Next level!");
while (theLeftSide.firstChild) {
theLeftSide.removeChild(theLeftSide.firstChild);
}
generateFaces();
}
theBody.onclick =
function gameOver() {
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
alert("Game Over!");
};
}
#leftSide {
background-color: red;
position: absolute;
width: 500px;
height: 500px;
left: 50px;
}
#rightSide {
position: absolute;
left: 600px;
width: 500px;
height: 500px;
--border-left: solid 10px;
}
img {
position: absolute;
width: 50px;
height: 50px;
}
<link rel="stylesheet" href="style.css">
<body onload="generateFaces()">
<h3>Matching Game</h3>
<h5>Please choose missed smile !</h5>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
<script src="jsCode.js"></script>
</body>
Updated your fiddle. Is this how you want it?
https://jsfiddle.net/ychq5rkm/12/
Specifically it uses document.ready() in the js instead of in the onload in the html. As was mentioned in the comments, you needed to actually call event.stopPropegation() because it was continuing up to the body each time and ending your game.

Javascript - Animation only working the first time the button is pressed

I have an animation which is called using onmousedown. I have another function which stops the animation (onmouseup).
The problem is that it only works the first time. By that I mean when I hold the button, it works and then stops when I stop pressing down but if I try to use either of the buttons after that first time nothing happens. It just won't move.
This is my HTML code (index.htm):
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<img id='player' src='img/player.png' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)"><--</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">--></button>
</div>
</body>
</html>
<script type='text/javascript' src='move.js'></script>
This is my javascript code (move.js):
var elem = document.getElementById("player");
function OnButtonDownl (button) {
var posl = document.getElementById("player").style.left;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
}}
function OnButtonUpl (button) {
clearInterval(idl);
}
var elem = document.getElementById("player");
function OnButtonDownr (button) {
var posr = document.getElementById("player").style.left;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
}}
function OnButtonUpr (button) {
clearInterval(idr);
}
Probably not important but here is my css (style.css):
body {
width: 100%;
height: 100%;
position:relative;
margin:0;
overflow:hidden;
}
#player {
position: absolute;
left:0;
bottom:0;
}
.buttons {
position:absolute;
right:0;
bottom:0;
}
Thanks for any help in advance.
You're running into 2 issues.
When you first get posl and posr, you're getting an empty string that JS is coercing to 0.
The -- and ++ won't work after you append the px (thus making posl and posr into string values)
Your posl-- (and posr++) can increment that coerced 0. That's why it works the first time through. The next time you mousedown the document.getElementById("player").style.left is a string — like "-1px" — that isn't interpreted as falsy (won't be coerced into 0). You can get around that by using parseInt() when you cache posl|posr but you have to provide a fallback of 0 because parseInt("") returns NaN…
You can work around that like so (with similar changes when you get posr):
var posl = parseInt( document.getElementById("player").style.left, 10 ) || 0;
var elem = document.getElementById("player");
function OnButtonDownl(button) {
//var posl = document.getElementById("player").style.left;
var posl = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
}
}
function OnButtonUpl(button) {
clearInterval(idl);
}
var elem = document.getElementById("player");
function OnButtonDownr(button) {
//var posr = document.getElementById("player").style.left;
var posr = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
}
}
function OnButtonUpr(button) {
clearInterval(idr);
}
body {
width: 100vw;// changed for example only
height: 100vh;// changed for example only
position: relative;
margin: 0;
overflow: hidden;
}
#player {
position: absolute;
left: 0;
bottom: 0;
}
.buttons {
position: absolute;
right: 0;
bottom: 0;
}
<img id='player' src='//placekitten.com/102/102' />
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)">Left</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">Right</button>
</div>
I was rewrite your code and it work (for me).
function Move(elem){
this.interval;
var posr = parseInt(getComputedStyle(document.getElementById("player")).left);
this.handleEvent = function(event) {
switch (event.type) {
case 'mousedown':
this.interval = setInterval(function() {
if (event.target.id == 'moveright') {
posr++;
} else if (event.target.id == 'moveleft'){
posr--;
}
document.getElementById("player").style.left = posr + 'px';
},5);
break;
case 'mouseup':
clearInterval(this.interval);
break;
}
}
elem.addEventListener('mousedown', this, false);
elem.addEventListener('mouseup', this, false);
}
var button_right = document.getElementById("moveright");
var button_left = document.getElementById("moveleft");
Move(button_right);
Move(button_left);
And in html you can remove js event listeners (this need only id).
First of all it is good practice to put your script tag inside your html tags:
<html>
<head>...</head>
<body>...</body>
<script type='text/javascript' src='move.js'></script>
</html>
Done that check this solution:
HTML:
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<img id='player' src='https://placeimg.com/54/45/any' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDown('left')" onmouseup="OnButtonUp()"><--</button>
<button id='moveright' onmousedown="OnButtonDown('right')" onmouseup="OnButtonUp()">--></button>
</div>
<script type='text/javascript' src='move.js'></script>
</body>
</html>
And js:
var nIntervId;
var b;
var elem = document.getElementById("player");
var posl = document.getElementById("player").style.left;
function OnButtonDown(button) {
b = button;
nIntervId = setInterval(frame, 5);
}
function frame() {
if(b==='left'){
posl--;
elem.style.left = posl + 'px';}
else{
posl++;
elem.style.left = posl + 'px';
}
}
function OnButtonUp() {
clearInterval(nIntervId);
}
http://output.jsbin.com/varaseheru/

Cannot retrieve instagram image caption using instafeed.js

I'm having a hard time trying to access the caption property within the image model. I'm creating a lightbox, where the image opens up full size on the page and has the image information underneath. In the after call back function I was able to create a function that expands the thumbnail image. However I can't access the caption or likes data.
I understand that I can do it using the template property, but that shows up when all of the images are loaded. I'm trying to show that information once the image is clicked. I keep getting an error. [gallery css test.html:35 Uncaught TypeError: Cannot read property 'custom' of undefined] when trying to retrieve the data from the custom property.
Note: In order to test the caption retrieval I changed the event listener on the thumbnails to the caption function. Normally I would attach it to the expandImage function.
Instafeed doc's
https://github.com/stevenschobert/instafeed.js
body {
margin: 0;
padding: 0;
background-color: black;
}
#container {
margin-left: auto;
margin-right: auto;
}
#galleryBox {
padding: 2%;
margin: 4%;
background-color: white;
}
#innerGallery {
margin-left: auto;
margin-right: auto;
text-align: center;
}
.thumbnail {
margin: 1%;
display: inline-block;
}
.location{
}
.caption {
}
.likes {
}
#backgroundChanger {
margin: 0;
padding: 0;
/*min-height: 150%;*/
/*min-width: 100%;*/
background-color: rgba(0,0,0,0.5);
left: 0;
right: 0;
top: 0;
bottom: 0;
position: fixed;
}
/*change lightbox to class*/
#lightBox {
left: 0;
right: 0;
top: 5%;
margin: 0 auto;
/*height: 800px;
width: 800px;*/
position: absolute;
}
#instafeed img {
object-fit: cover;
height: 20em;
width: 20em;
margin: 1%;
}
<!DOCTYPE html>
<html>
<head>
<title>Gallery</title>
<link rel="stylesheet" type="text/css" href="style2.css">
</head>
<body>
<div id="container">
<div id="galleryBox">
<div id="innerGallery"><div id="instafeed"></div></div>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="js/instafeed.min.js"></script>
<script type="text/javascript">
function init() {
var feed = new Instafeed({
get: 'user',
userId: '1418648047',
resolution: 'standard_resolution',
template: '<img class="thumbnail" src="{{model.images.standard_resolution.url}}" />',
clientId: '66e8640ecc1c4145af1bb497cda6897c',
// custom: '<div class="location">{{location}}</div><div class="caption">{{caption}}</div><div class="likes">{{likes}}</div>',
custom: {
images: [],
currentImage: 0,
showImage: function () {
var result, image;
image = this.options.custom.images[this.options.custom.currentImage];
result = this._makeTemplate(this.options.template, {
model: image,
id: image.id,
link: image.link,
image: image.images[this.options.resolution].url,
caption: this._getObjectProperty(image, 'caption.text'),
likes: image.likes.count,
comments: image.comments.count,
location: this._getObjectProperty(image, 'location.name')
});
var imageInfoDiv = document.createElement("div");
imageInfoDiv.innerHTML = result;
}
},
after: function() {
var backgroundChanger = document.createElement("div");
backgroundChanger.id = "backgroundChanger";
var lightBox = document.createElement("div");
lightBox.id = "lightBox";
var expandedImg = document.createElement("img");
// var imageInfoDiv = document.createElement("div");
var thumbnails = document.getElementsByClassName("thumbnail");
var innerGallery = document.getElementById("innerGallery");
for (i = 0; i < thumbnails.length; i++) {
thumbnails[i].addEventListener("click", caption);
}
function caption(imageInfoDiv) {
console.log(feed.options.custom.showImage(imageInfoDiv));
lightBox.appendChild(feed.options.custom.showImage(imageInfoDiv));
}
function expandImage() {
expandImage = this;
expandedImg.src = this.src;
document.body.appendChild(backgroundChanger);
backgroundChanger.appendChild(lightBox);
lightBox.appendChild(expandedImg);
lightBox.style.width = expandedImg.width + "px";
expandedImg.addEventListener("click", removeImage);
backgroundChanger.addEventListener("click", removeImage);
}
//TO DO: Add captions, favorite. Next previous. Alt tag? Work on canvas
function removeImage() {
document.body.removeChild(backgroundChanger);
backgroundChanger.removeChild(lightBox);
lightBox.removeChild(expandedImg);
expandedImg.removeEventListener("click", removeImage);
backgroundChanger.removeEventListener("click", removeImage);
}
// feed.next();
}
});
feed.run();
// var hew = Instafeed.prototype.
var rgb = getAverageRGB(document.getElementById("i"));
document.body.style.backgroundColor = "rgb('+rgb.r+', '+rgb.b+', '+rgb.g+')";
function getAverageRGB(imgEl) {
var blockSize = 5, //every 5 pixels
defaultRGB = {r:0, g:0, b:0},
canvas = document.createElement,
context = canvas.getContext && canvas.getContext('2d'),
data, width, height,
i = -4,
length,
rgb = {r:0, g:0, b:0},
count = 0;
if (!context) {
return defaultRGB;
}
height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
context.drawImage(imgEl, 0, 0);
try {
data = context.getImageData(0, 0, width, height);
} catch(e) {
console.log("x");
return defaultRGB;
}
length = data.data.length;
while ((i += blockSize * 4) < length) {
++count;
rgb.r += data.data[i];
rgb.g += data.data[i+1];
rgb.b += data.data[i+2];
}
rgb.r = ~~(rgb.r/count);
rgb.g = ~~(rgb.g/count);
rgb.b = ~~(rgb.b/count);
return rgb;
}
};
window.onload = init();
</script>
</html>
Cannot read property 'custom' of undefined means, options is not exists on object this. that's because the context of showImage is bind to object custom instead of object feed. That means, you are calling custom.options.custom.
use this.images[this.currentImage] instead if this represented to custom itself, use feed if this represented to feed object

Change CSS Background Image for KEYBIND Javascript DIV

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.

DIV POP UP containing clickable images using javascript

I have an image button which changes images with a click of a button . This is the following code
function changeImg(thisImg)
{
var altImg = "http://ww1.prweb.com/prfiles/2011/10/12/8875514/star_white.jpg";
var tmpImg = null;
function changeImg(thisImg) {
tmpImg = thisImg.src;
thisImg.src = altImg;
altImg = tmpImg;
}
this is the fiddle http://jsfiddle.net/pUbrv/ which I did previously for clickable images
<img alt="" src="http://www.gettyicons.com/free-icons/136/stars/png/256/star_gold_256.png" id="imgClickAndChange" onclick="changeImg(this)" />
Instead of just chnaging the image by click of a button , I want to pop up a div which contains clickable images after I click the image in the div , the image choud change . Can please anybody help me?
Here is simple Javascript solution.
DEMO
HTML
<body>
<img alt="" src="http://www.gettyicons.com/free-icons/136/stars/png/256/star_gold_256.png" id="imgClickAndChange" onclick="myfunction(this)" />
</body>
SCRIPT
var altImg = "http://ww1.prweb.com/prfiles/2011/10/12/8875514/star_white.jpg";
var tmpImg = null;
function changeImg(thisImg) {
tmpImg = thisImg.src;
thisImg.src = altImg;
altImg = tmpImg;
}
function myfunction(ele) {
var pop=new myPop();
pop.popOut(ele);
}
function myPop() {
this.square = null;
this.overdiv = null;
this.popOut = function(ele) {
tmpImg = ele.src;
//filter:alpha(opacity=25);-moz-opacity:.25;opacity:.25;
this.overdiv = document.createElement("div");
this.overdiv.className = "overdiv";
this.square = document.createElement("div");
this.square.className = "square";
this.square.Code = this;
var msg = document.createElement("div");
msg.className = "msg";
msg.innerHTML = '<img alt="" src="'+altImg+'" id="imgClickAndChange" />';
altImg = tmpImg;
this.square.appendChild(msg);
var closebtn = document.createElement("button");
closebtn.onclick = function() {
this.parentNode.Code.popIn();
}
closebtn.innerHTML = "Close";
this.square.appendChild(closebtn);
document.body.appendChild(this.overdiv);
document.body.appendChild(this.square);
}
this.popIn = function() {
if (this.square != null) {
document.body.removeChild(this.square);
this.square = null;
}
if (this.overdiv != null) {
document.body.removeChild(this.overdiv);
this.overdiv = null;
}
}
}
CSS
div.overdiv { filter: alpha(opacity=75);
-moz-opacity: .75;
opacity: .75;
background-color: #c0c0c0;
position: absolute;
top: 0px;
left: 0px;
width: 100%; height: 100%; }
div.square { position: absolute;
top: 200px;
left: 200px;
background-color: Menu;
border: #f9f9f9;
height: 200px;
width: 300px; }
div.square div.msg { color: #3e6bc2;
font-size: 15px;
padding: 15px; }
Pollisbly the jQuery UI dialog can help you.
Since the changing of images you have already implemented, you just need to put the images in the dialog.
Also you may like the modal functionality of the dialog.
Edit
If you don't want to use jQuery UI, then here is what you can do:
Create a new div.
Initially make it hidden or set its display property to none.
When user clicks on the image, make this div visible.
Set its position to absolute and set its left and top corrdinates as you want.
Add the image this div,
and finally add the event handler to this div for changing the images.

Categories

Resources