Custom confirmbox, wait for button click in function Javascript - javascript

I want to make a confirmbox that returns true or false. If the user clicks OK it has to return true and if the user clicks Cancel or the cross in the upperleft corner it has to return false. But I'm stuck at the point the user clicks the button. I've already tried using callbacks but it could not help me to achieve what I would like to have.
So far I have this:
Fiddle
function SimpleAlert( title, text, cancel)
{
var stylesheet = document.createElement('style');
stylesheet.id="SimpleAlertStylesheet";
stylesheet.innerHTML="#SimpleAlertOverlay { top:0px; bottom:0px; left:0px; right:0px; position:fixed; background:rgba(230,230,230,0.5); height:100%; width:100%; font-family:Sans-serif; } #SimpleAlertLightbox { background:#f5f5f5; border-radius:3px; width:400px; box-shadow: 0px 0px 15px rgba(0,0,0,0.3); } .SimpleAlertTopbar { border-radius:3px; background:#e5e5e5; height:24px; color:#444; line-height:24px; padding:0px 5px; font-weight:bold; font-size:14px; border-bottom:1px solid #DDD } .SimpleAlertCross1 { margin:5px 15px 0px 0px; opacity:0.7; } .SimpleAlertCross2 { margin:5px 15px 0px 0px; opacity:0.5; } .SimpleAlertCross1:hover { opacity:1; } .SimpleAlertTopbar > div { float:left } .SimpleAlertMessagediv { padding:20px 40px; font-size:14px; color:#444; } .SimpleAlertButtondiv { height:26px; line-height:26px; padding:0px 40px 18px 40px; } .SimpleAlertButtondiv button { height:26px; background:#f9f9f9; border:1px solid #CCC; color:#444; float:right; } .SimpleAlertButtondiv button:hover { border:1px solid #AAA; } .SimpleAlertButtondiv button:focus { outline:none; }";
var overlay = document.createElement('div');
overlay.id = 'SimpleAlertOverlay';
var lightbox = document.createElement('div');
lightbox.id = 'SimpleAlertLightbox';
overlay.appendChild(lightbox);
var topbar = document.createElement('div');
topbar.setAttribute("class", "SimpleAlertTopbar");
lightbox.appendChild(topbar);
var crossdiv = document.createElement('div');
topbar.appendChild(crossdiv);
var crossspan = document.createElement('span');
crossdiv.appendChild(crossspan);
var cross = document.createElement('img');
if(cancel)
{
cross.setAttribute("class", "SimpleAlertCross1");
}
else
{
cross.setAttribute("class", "SimpleAlertCross2");
}
cross.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDBGMDEwRUNCQTQyMTFFMzlBNjZDNzQ4QzkxQTI1QkYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NDBGMDEwRURCQTQyMTFFMzlBNjZDNzQ4QzkxQTI1QkYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo0MEYwMTBFQUJBNDIxMUUzOUE2NkM3NDhDOTFBMjVCRiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo0MEYwMTBFQkJBNDIxMUUzOUE2NkM3NDhDOTFBMjVCRiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pp1kTM8AAAFGSURBVHjalJI9S0JRGMd/VwKnbKkQvOpUBqIOOrj4DTTEanKqzSGQvknt9gXiIgp+BScXdZEKB18GockGscHTc7zdazcs8g+/w3l5nvM/L4+hlMJVKnUo7Z2QF06/ZgdCU3ig231zQg03MZm8kLYmHLBdc+GGXs/aJCYSOulJj/lb2uWKft8yVDx+JINXIcD/pJ1PfKxWt0JAYE2pBJWK3c9moVqFYBB33Y6t+lDqHH1ch3YbTBPKZSgUYDaD6RRPjFJ57Xj2bTcYj6HTgXQalktoNPCs28T21p2fWiw2fSfYqw/tOPDsFgpBLme7+v1QLG5zHOrEpmdS320uD1eTL63XIZOxj+1NbBkqGj0W65ddv8MugEhktwIYjaxNyYXDl9I+Cvu/JL0L1/LqlrdWtUzTKXL5QGL69YRnoSXcM5m4Rf4pwABHDba2DxAS7QAAAABJRU5ErkJggg==';
crossspan.appendChild(cross);
var titlediv = document.createElement('div');
titlediv.innerHTML = title;
topbar.appendChild(titlediv);
var messagediv = document.createElement('div');
messagediv.setAttribute("class", "SimpleAlertMessagediv");
messagediv.innerHTML = text;
lightbox.appendChild(messagediv);
var buttondiv = document.createElement('div');
buttondiv.setAttribute("class", "SimpleAlertButtondiv");
lightbox.appendChild(buttondiv);
var okbutton = document.createElement('button');
okbutton.innerHTML="OK";
buttondiv.appendChild(okbutton);
document.body.appendChild(overlay);
document.body.appendChild(stylesheet);
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
function CenterDiv(elementId){
var main = document.getElementById(elementId);
var wi=main.offsetWidth;
var he=main.offsetHeight;
var marginleft = wi / 2;
var margintop = he / 2;
main.style.marginLeft="-" + marginleft;
main.style.marginTop="-" + margintop;
main.style.position="absolute";
main.style.left="50%";
main.style.top="50%"
}
CenterDiv('SimpleAlertLightbox');
if(cancel)
{
var cancelbutton = document.createElement('button');
cancelbutton.innerHTML="Cancel";
cancelbutton.style.marginRight="30px";
buttondiv.appendChild(cancelbutton);
cancelbutton.addEventListener('click', SimpleAlertCancel , false);
}
cross.addEventListener('click', SimpleAlertCancel , false);
okbutton.addEventListener('click', SimpleAlertOK , false);
function SimpleAlertCancel()
{
document.body.removeChild(document.getElementById('SimpleAlertOverlay'));
document.body.removeChild(document.getElementById('SimpleAlertStylesheet'));
}
function SimpleAlertOK()
{
document.body.removeChild(document.getElementById('SimpleAlertOverlay'));
document.body.removeChild(document.getElementById('SimpleAlertStylesheet'));
}
}
What I'm trying to achieve is:
if(SimpleAlert('title', 'text', true))
{
//User clicked OK
}
else
{
//User clicked Cancel
}
I am looking for something like the system functions: alert(), confirm() and prompt(). These functions pause all Javascript and wait until a button has been clicked.
I have browsed throught all the folders of the internet browsers installed on my computer to find the above functions declared but i couldn't find them.
Here is an image of the alertbox for the person that doesn't open the fiddle ;-)
I hope you can help me to get a step closer.

You can't do that with Javascript, as it is asynchronous, the code continues executing even if the window/div is shown.
For managing the actions, execute the code you need on the onclick events on each of the "OK" and "Cancel" buttons

Related

Radio input onclick function won't run

I know the pictures don't show up, but that's not the issue. The text after the inputs won't show because the function won't restart. Do radio buttons support onclick? Thanks for the help! I am now adding this text because the site won't let me post this question unless I add more text. Sorry.
var gameContainer = document.getElementById("game-container");
var speechBox = document.createElement("DIV");
speechBox.id = "speech-box";
var speechP = document.createElement("P");
speechP.id = "speech-p"
var speech = document.createTextNode("");
var speechNum = 0;
var text = true;
function startGame() {
var startButton = document.getElementById("start-button");
gameContainer.removeChild(startButton); //button disappears
var logo = document.createElement("IMG");
logo.src = "index/src/img/logo.gif";
gameContainer.appendChild(logo);
logo.id="logo"; //logo appears
var sublogo = document.createElement("P");
var sublogoText = document.createTextNode("Yellow Diamond Version");
sublogo.appendChild(sublogoText);
gameContainer.appendChild(sublogo);
sublogo.id="sub-logo";
var sublogoImg = document.createElement("IMG");
sublogoImg.src = "index/src/img/yellowDiamondFace.png"
gameContainer.appendChild(sublogoImg);
sublogoImg.id = "sub-logo-img";
setTimeout(preLogoFade,3000);
function preLogoFade() {
var logoOpacity = .9;
var logoInterval = setInterval(function(){LogoFade()},100);
function LogoFade() {
logo.style.opacity=logoOpacity;
sublogo.style.opacity=logoOpacity;
sublogoImg.style.opacity=logoOpacity;
logoOpacity-=.1;
if(logoOpacity<=0){
gameContainer.removeChild(logo);
gameContainer.removeChild(sublogo);
gameContainer.removeChild(sublogoImg);
clearInterval(logoInterval);
setTimeout(mainMenu,200);
}
} //LogoFade Func End
} //preLogoFade Func End
} //startGame Func End
function mainMenu() {
var mainMenuBox = document.createElement("DIV");
mainMenuBox.id = "main-menu-box";
var mainMenuBoxNew = document.createElement("P");
mainMenuBoxNew.className = "main-menu-box-p";
mainMenuBoxNew.innerHTML = "New Game";
var mainMenuBoxNewPic = document.createElement("IMG");
mainMenuBoxNewPic.className = "main-menu-box-pic";
mainMenuBoxNewPic.src = "index/src/img/red.gif"
mainMenuBoxNew.appendChild(mainMenuBoxNewPic);
mainMenuBoxNew.onmouseenter = function(){mainMenuBoxNewPic.src = "index/src/img/redAnimated.gif";}
mainMenuBoxNew.onmouseleave = function(){mainMenuBoxNewPic.src = "index/src/img/red.gif";}
mainMenuBoxNew.onclick = function(){mainMenuNewFunc();}
function mainMenuNewFunc() {
gameContainer.removeChild(mainMenuBox);
preProfessorOpen();
}
var mainMenuBoxSave = document.createElement("P");
mainMenuBoxSave.className = "main-menu-box-p";
mainMenuBoxSave.innerHTML = "Save Code";
var mainMenuBoxSavePic = document.createElement("IMG");
mainMenuBoxSavePic.className = "main-menu-box-pic";
mainMenuBoxSavePic.src = "index/src/img/binary.jpg";
mainMenuBoxSave.appendChild(mainMenuBoxSavePic);
mainMenuBoxSave.onmouseenter = function(){mainMenuBoxSavePic.src = "index/src/img/binaryAnimated.gif";}
mainMenuBoxSave.onmouseleave = function(){mainMenuBoxSavePic.src = "index/src/img/binary.jpg";}
var mainMenuBoxCheat = document.createElement("P");
mainMenuBoxCheat.className = "main-menu-box-p";
mainMenuBoxCheat.innerHTML = "Cheat Code";
var mainMenuBoxCheatPic = document.createElement("IMG");
mainMenuBoxCheatPic.className = "main-menu-box-pic";
mainMenuBoxCheatPic.src = "index/src/img/cheatCode.jpg";
mainMenuBoxCheat.appendChild(mainMenuBoxCheatPic);
mainMenuBoxCheat.onmouseenter = function(){mainMenuBoxCheatPic.src = "index/src/img/cheatCodeAnimated.gif";}
mainMenuBoxCheat.onmouseleave = function(){mainMenuBoxCheatPic.src = "index/src/img/cheatCode.jpg";}
gameContainer.appendChild(mainMenuBox);
mainMenuBox.appendChild(mainMenuBoxNew);
mainMenuBox.appendChild(mainMenuBoxSave);
mainMenuBox.appendChild(mainMenuBoxCheat);
}
function preProfessorOpen() {
document.body.style.backgroundImage = "url(index/src/img/professor.png)";
gameContainer.appendChild(speechBox);
speechBox.appendChild(speechP);
speechP.innerHTML = "Welcome to the world of Pokémon, clod!";
speechBox.onclick = function(){professorOpen();}
function professorOpen() {
speechNum++;
switch(speechNum) {
case 1:
speech = "I am Yellow Diamond – reduced to introducing Pokémon Spin-Offs.";
break;
case 2:
speech = "This world of clods is widely inhabited by creatures known as Pokémon.";
break;
case 3:
speech = "These mysterious creature can be found in every corner of this world...";
break;
case 4:
speech = "Some run across the plains, others fly through the skies, and others yet swim deep in the oceans...";
break;
case 5:
speech = "Clods live together with these Pokémon, lending their little strength to one another to live and prosper.";
break;
case 6:
speech = "Let's get started with some quick questions...<br>Are you a boy? Or are you a girl?<br>(Probably a boy if Alex shared this with you.)";
break;
case 7:
speechBox.onclick = ""
speechBox.innerHTML = '<br> \
<input type="radio" class="gender-inpt" id="male" name="gender"> \
<label for="male" class="gender-lbl" id="male-lbl">Boy</label> \
<br> \
<input type="radio" class="gender-inpt" id="female" name="gender"> \
<label for="female" class="gender-lbl" id="female-lbl">Girl</label>'
document.getElementsByClassName("gender-inpt").onclick = function(){genderFunc();}
document.getElementsByClassName("gender-lbl").onclick = function(){genderFunc();}
function genderFunc() {
window.inptM = document.getElementById("male");
professorOpen();
}
break;
case 8:
speechBox.onclick = function(){professorOpen();}
speechBox.innerHTML = "";
speechBox.appendChild(speechP);
if(inptM.checked) {gender="boy";} else {gender="girl";}
speech = "So, you're a " + gender + "?";
}
if(text){speechP.innerHTML = speech;};
text = true;
} //professOpen Func End
} //preProfessOpen Func End
body {
background-color:black;
background-repeat:no-repeat; background-size:300px 700px; background-position:center top;
}
#game-container{
width:800px; height:700px;
border:1px solid white;
margin:0 auto;
overflow:hidden;
padding:0;
}
#start-button{
width:100px; height:40px;
position:relative; top:330px; left:350px;
background-color:red;
border:1px solid white; border-bottom-width:2px; border-top-width:0px;
font-size:125%;
cursor:pointer;
}
#start-button:hover{
color:white;
}
#logo{
width:100%; height:300px;
position:relative;
z-index:3;
}
#sub-logo{
text-shadow: 1px 0 5px white, -1px 0 5px white, 0 1px 5px white, 0 -1px 5px white;
color:#FEFF00;
text-align:center;
font-size:50px;
position:relative; bottom:70px; left:15px;
z-index:2;
}
#sub-logo-img{
width:550px; height:405px;
margin:auto;
position:relative; left:140px; bottom:170px;
z-index:1;
}
#main-menu-box{
width:200px;
margin:0 auto;
border:1px solid #444444; border-radius:4px;
position:relative; top:300px;
cursor:pointer;
}
.main-menu-box-p{
border-radius:4px;
background-color:#EEEEEE;
border:1px solid #666666;
padding-left:20px; padding-top:3px;
margin:0; margin-bottom:1px;
}
#speech-box{
width:60%; height:100px;
background-color:white;
color:black;
font-size:125%;
border:1px solid #999999; border-radius:20px;
margin:0 auto;
padding:0 10px;
opacity:.8;
position:relative; bottom:10px; top:600px;
cursor:pointer;
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
.main-menu-box-pic{
width:20px; height:20px;
float:right;
position:relative; bottom:3px;
}
.gender-inpt{
float:left;
margin-right:10px;
}
#male-lbl{color:#0000FF;}
#female-lbl{color:#FF0066;}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>Game</title>
<meta name="robots" content="noindex, nofollow">
<meta name="author" content="Some Nerd.">
<link rel="icon" href="http://pokeadventuretime.blogspot.com.br/favicon.ico">
<link rel="stylesheet" href="index/src/style.css">
</head>
<body>
<div id="game-container">
<button id="start-button" onclick="startGame()">Start</button>
</div>
<script src="index/src/src.js"></script>
</body>
</html>
Few things here. First of all, getElementsByClassName returns an array-like object, so it's basically a list of all the elements it found with that class. If you want to set an onclick, you need to pick a specific element or you will just be trying to set an onclick on the list which does nothing.
Secondly, you already have a the code which you want executed upon click wrapped up in a function (genderFunc) so there's no need to wrap it up again. so what you want to do here is:
var inputList = document.getElementsByClassName("gender-inpt")
for( var i = 0; i< inputList.length; i++){
inputList[i].onclick = genderFunc;
}
Alternately, you're already generating the html for the radio buttons dynamically so you could just set the onclick there:
speechBox.innerHTML = '
<br> \
<input type="radio" class="gender-inpt" id="male" name="gender" onclick "genderFunc"> \
<label for="male" class="gender-lbl" id="male-lbl">Boy</label> \
<br> \
<input type="radio" class="gender-inpt" id="female" name="gender" onclick "genderFunc"> \
<label for="female" class="gender-lbl" id="female-lbl">Girl</label>'

Remove height of Div with Height: Auto? JS/CSS

So I have finished building the .JS for my video player and somehow my positioning is making my div stretch (See here: http://prntscr.com/8tsl4m)
I want to remove that part but I am using six-columns class width from skeleton framework, so the div width dynamically changes. Therefore I cannot just define a height because it has to be auto.
Can I remove this with a line of JS or some CSS attribute that I am missing?
Keep in mind that I am just starting to figure out what JS is even used for, and and intermediate in CSS and HTML.
If you need my code then here it is:
$(document).ready(function(){
//INITIALIZE
var video = $('#myVideo');
//remove default control when JS loaded
video[0].removeAttribute("controls");
$('.control').show().css({'bottom':45});
$('.loading').fadeIn(500);
$('.caption').fadeIn(500);
//before everything get started
video.on('loadedmetadata', function() {
$('.caption').animate({'top':-380},300);
//set video properties
$('.current').text(timeFormat(0));
$('.duration').text(timeFormat(video[0].duration));
updateVolume(0, 0.7);
//start to get video buffering data
setTimeout(startBuffer, 150);
//bind video events
$('.videoContainer')
.append('<div id="init"></div>')
.hover(function() {
$('.control').stop().animate({'bottom':45}, 500);
$('.caption').stop().animate({'top':-360}, 500);
}, function() {
if(!volumeDrag && !timeDrag){
$('.control').stop().animate({'bottom':45}, 500);
$('.caption').stop().animate({'top':-380}, 500);
}
})
.on('click', function() {
$('#init').remove();
$('.btnPlay').addClass('paused');
$(this).unbind('click');
video[0].play();
});
$('#init').fadeIn(200);
});
//display video buffering bar
var startBuffer = function() {
var currentBuffer = video[0].buffered.end(0);
var maxduration = video[0].duration;
var perc = 100 * currentBuffer / maxduration;
$('.bufferBar').css('width',perc+'%');
if(currentBuffer < maxduration) {
setTimeout(startBuffer, 500);
}
};
//display current video play time
video.on('timeupdate', function() {
var currentPos = video[0].currentTime;
var maxduration = video[0].duration;
var perc = 100 * currentPos / maxduration;
$('.timeBar').css('width',perc+'%');
$('.current').text(timeFormat(currentPos));
});
//CONTROLS EVENTS
//video screen and play button clicked
video.on('click', function() { playpause(); } );
$('.btnPlay').on('click', function() { playpause(); } );
var playpause = function() {
if(video[0].paused || video[0].ended) {
$('.btnPlay').addClass('paused');
video[0].play();
}
else {
$('.btnPlay').removeClass('paused');
video[0].pause();
}
};
//speed text clicked
$('.btnx1').on('click', function() { fastfowrd(this, 1); });
$('.btnx3').on('click', function() { fastfowrd(this, 3); });
var fastfowrd = function(obj, spd) {
$('.text').removeClass('selected');
$(obj).addClass('selected');
video[0].playbackRate = spd;
video[0].play();
};
//stop button clicked
$('.btnStop').on('click', function() {
$('.btnPlay').removeClass('paused');
updatebar($('.progress').offset().left);
video[0].pause();
});
//fullscreen button clicked
$('.btnFS').on('click', function() {
if($.isFunction(video[0].webkitEnterFullscreen)) {
video[0].webkitEnterFullscreen();
}
else if ($.isFunction(video[0].mozRequestFullScreen)) {
video[0].mozRequestFullScreen();
}
else {
alert('Your browsers doesn\'t support fullscreen');
}
});
//light bulb button clicked
$('.btnLight').click(function() {
$(this).toggleClass('lighton');
//if lightoff, create an overlay
if(!$(this).hasClass('lighton')) {
$('body').append('<div class="overlay"></div>');
$('.overlay').css({
'position':'absolute',
'width':100+'%',
'height':$(document).height(),
'background':'#000',
'opacity':0.9,
'top':0,
'left':0,
'z-index':999
});
$('.videoContainer').css({
'z-index':1000
});
}
//if lighton, remove overlay
else {
$('.overlay').remove();
}
});
//sound button clicked
$('.sound').click(function() {
video[0].muted = !video[0].muted;
$(this).toggleClass('muted');
if(video[0].muted) {
$('.volumeBar').css('width',0);
}
else{
$('.volumeBar').css('width', video[0].volume*100+'%');
}
});
//VIDEO EVENTS
//video canplay event
video.on('canplay', function() {
$('.loading').fadeOut(100);
});
//video canplaythrough event
//solve Chrome cache issue
var completeloaded = false;
video.on('canplaythrough', function() {
completeloaded = true;
});
//video ended event
video.on('ended', function() {
$('.btnPlay').removeClass('paused');
video[0].pause();
});
//video seeking event
video.on('seeking', function() {
//if video fully loaded, ignore loading screen
if(!completeloaded) {
$('.loading').fadeIn(200);
}
});
//video seeked event
video.on('seeked', function() { });
//video waiting for more data event
video.on('waiting', function() {
$('.loading').fadeIn(200);
});
//VIDEO PROGRESS BAR
//when video timebar clicked
var timeDrag = false; /* check for drag event */
$('.progress').on('mousedown', function(e) {
timeDrag = true;
updatebar(e.pageX);
});
$(document).on('mouseup', function(e) {
if(timeDrag) {
timeDrag = false;
updatebar(e.pageX);
}
});
$(document).on('mousemove', function(e) {
if(timeDrag) {
updatebar(e.pageX);
}
});
var updatebar = function(x) {
var progress = $('.progress');
//calculate drag position
//and update video currenttime
//as well as progress bar
var maxduration = video[0].duration;
var position = x - progress.offset().left;
var percentage = 100 * position / progress.width();
if(percentage > 100) {
percentage = 100;
}
if(percentage < 0) {
percentage = 0;
}
$('.timeBar').css('width',percentage+'%');
video[0].currentTime = maxduration * percentage / 100;
};
//VOLUME BAR
//volume bar event
var volumeDrag = false;
$('.volume').on('mousedown', function(e) {
volumeDrag = true;
video[0].muted = false;
$('.sound').removeClass('muted');
updateVolume(e.pageX);
});
$(document).on('mouseup', function(e) {
if(volumeDrag) {
volumeDrag = false;
updateVolume(e.pageX);
}
});
$(document).on('mousemove', function(e) {
if(volumeDrag) {
updateVolume(e.pageX);
}
});
var updateVolume = function(x, vol) {
var volume = $('.volume');
var percentage;
//if only volume have specificed
//then direct update volume
if(vol) {
percentage = vol * 100;
}
else {
var position = x - volume.offset().left;
percentage = 100 * position / volume.width();
}
if(percentage > 100) {
percentage = 100;
}
if(percentage < 0) {
percentage = 0;
}
//update volume bar and video volume
$('.volumeBar').css('width',percentage+'%');
video[0].volume = percentage / 100;
//change sound icon based on volume
if(video[0].volume == 0){
$('.sound').removeClass('sound2').addClass('muted');
}
else if(video[0].volume > 0.5){
$('.sound').removeClass('muted').addClass('sound2');
}
else{
$('.sound').removeClass('muted').removeClass('sound2');
}
};
//Time format converter - 00:00
var timeFormat = function(seconds){
var m = Math.floor(seconds/60)<10 ? "0"+Math.floor(seconds/60) : Math.floor(seconds/60);
var s = Math.floor(seconds-(m*60))<10 ? "0"+Math.floor(seconds-(m*60)) : Math.floor(seconds-(m*60));
return m+":"+s;
};
});
/* video container */
.videoContainer{
width: 100%;
height:auto;
position:relative;
overflow:hidden;
background-color: #f2f5f8;
color: #383737;
border: 0px solid #f2f5f8;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;}
/* video caption css */
.caption{
display:none;
position: relative;
top: -100%;
background-color: #f2f5f8;
font-size:20px;
font-weight:bold;
background-color: #f2f5f8;
}
/*** VIDEO CONTROLS CSS ***/
/* control holder */
.control{
background-color: #f2f5f8;
font-family: Cabin;
color: #383737;
position:relative;
bottom: 75px;
left:0;
width:100%;
z-index:5;
display:none;
height: 40px;
}
/* control top part */
.topControl{
height:11px;
border-bottom:1px solid #404040;
padding:1px 5px;
}
/* control bottom part */
.btmControl{
clear:both;
height: 6px;
opacity: 0.5;
background-color: #eef2f6;
}
.control div.btn {
float:left;
width:34px;
height:30px;
padding:0 5px;
border-right:1px solid #404040;
cursor:pointer;
}
.control div.text{
font-size:12px;
font-weight:bold;
line-height:30px;
text-align:center;
font-family:verdana;
width:20px;
border:none;
color: #383737;
}
.control div.btnPlay{
background:url(images/play.png) no-repeat 0 0;
border-left:1px solid #404040;
}
.control div.paused{
background:url(images/pause.png) no-repeat 0 0px;
}
.control div.btnStop{
background:url(control.png) no-repeat 0 -60px;
}
.control div.spdText{
border:none;
font-size:14px;
line-height:30px;
font-style:italic;
}
.control div.selected{
font-size:15px;
color: #383737;
}
.control div.sound{
background:url(control.png) no-repeat -88px -30px;
border:none;
float:right;
}
.control div.sound2{
background:url(control.png) no-repeat -88px -60px !important;
}
.control div.muted{
background:url(control.png) no-repeat -88px 0 !important;
}
.control div.btnFS{
background:url(control.png) no-repeat -44px 0;
float:right;
}
.control div.btnLight{
background:url(control.png) no-repeat -44px -60px;
border-left:1px solid #404040;
float:right;
}
.control div.lighton{
background:url(control.png) no-repeat -44px -30px !important;
}
/* PROGRESS BAR CSS */
/* Progress bar */
.progress {
width:85%;
position:relative;
float:left;
cursor:pointer;
height: 6px;
background-color: #eef2f6;
}
.progress span {
height:100%;
position:absolute;
top:0;
left:0;
display:block;
}
.timeBar{
z-index:10;
width:0;
height: 6px;
background-color: #db7560;
}
.bufferBar{
z-index:5;
width:0;
height: 6px;
opacity: 0.5;
background-color: #eef2f6;
}
/* time and duration */
.time{
width:15%;
float:right;
text-align:center;
font-size:11px;
line-height:12px;
}
/* VOLUME BAR CSS */
/* volume bar */
.volume{
position:relative;
cursor:pointer;
width:70px;
height:10px;
float:right;
margin-top:10px;
margin-right:10px;
}
.volumeBar{
display:block;
height:100%;
position:absolute;
top:0;
left:0;
background-color:#eee;
z-index:10;
}
/* OTHERS CSS */
/* video screen cover */
.loading, #init{
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
background:url(images/loading.gif) no-repeat 50% 50%;
z-index:2;
display:none;
z-index: 100;
}
#init{
background:url(images/bigplay.png) no-repeat 50% 50% !important;
cursor:pointer;
z-index: 50;
}
<div class="six columns">
<div class="videoContainer">
<video id="myVideo" controls preload="auto" poster="images/1-thm.png" width="600" height="350" >
<source src="video.mp4" type="video/mp4" />
<p>Your browser does not support the video tag.</p>
</video>
<div class="caption">Screamer 2015 Intro</div>
<div class="control">
<div class="topControl">
<div class="progress">
<span class="bufferBar"></span>
<span class="timeBar"></span>
</div>
<div class="time">
<span class="current"></span> /
<span class="duration"></span>
</div>
</div>
<div class="btmControl">
<div class="btnPlay btn" title="Play/Pause video"></div>
<div class="btnStop btn" title="Stop video"></div>
<div class="spdText btn">Speed: </div>
<div class="btnx1 btn text selected" title="Normal speed">x1</div>
<div class="btnx3 btn text" title="Fast forward x3">x3</div>
<div class="btnFS btn" title="Switch to full screen"></div>
<div class="btnLight lighton btn" title="Turn on/off light"></div>
<div class="volume" title="Set volume">
<span class="volumeBar"></span>
</div>
<div class="sound sound2 btn" title="Mute/Unmute sound"></div>
</div>
</div>
<div class="loading"></div>
</div>
</div>
In your div btmControl, there is the code
<div class="volume" title="Set volume">
<span class="volumeBar"></span>
</div>
for which I cannot see the use right now.
Try changing the corresponding height value in the css part (.volume and .volumeBar) or consider removing it (if it really is not useful)
Because it is set to
display:block;
it should create a new line and not fill in a row along with the other divs.
So display:inline; will also provide a possible solution
Furthermore, the following divs will also be aligned in a new line. I propose this is the line break you do not want to have...
(For an example of display:block effect click here)
But anyway, a fiddle version for this problem would be of great help!

Infinite gallery with multiple visible images

I'm looking to create something like the following has on top of their site.
http://www.vogue.com/
The auto-scrolling slideshow that has multiple images shown. (1, 2, 3) then (2, 3, 4). It cycles through them eventually depending on how many there are. Each image is also in a separate div, where I believe the overlay is being placed for the two outside images that aren't being focused.
I'm not that well versed in javascript to create something like this myself from scratch, and haven't found a jquery slideshow that allows for the multiple images to be seen at a given time. The closest I've found is a plugin that scrolls through 3 images at a time, and didn't auto-scroll.
Does anyone know how this would be easily accomplished with the given specs? I need it to perform pretty much how it does on the vogue site. Thanks in advance.
jsBin demo
jQuery:
// infinite Gallery - script by roXon, design idea by "Vogue(R)"
$(function(){
var c = 0; // COUNTER // SET HERE DESIRED START SLIDE NUMBER (zero based)
var speed = 300; // ANIMATION SPEED
var pause = 3500; // ANIMATION PAUSE
var $slider = $('.carousel-slider');
var $sli = $slider.find('.carousel-content');
var $btns = $('#btn-left, #btn-right');
/* DO NOT EDIT BELOW */
var sliN = $sli.length;
$('.carousel').clone().appendTo( $('.carousel:gt(0)') ); /*CLONE SLIDERS*/
var m = 0;
var w = $slider.closest('div').width();
var intv;
$slider = $('.carousel-slider'); // all
$slider.width(w*2);
// rearrange
$slider.eq(0).find('.carousel-content:lt('+(c)+')').appendTo( $slider.eq(0) );
$slider.eq(1).find('.carousel-content:lt('+(c-1)+')').appendTo( $slider.eq(1) );
$slider.eq(2).find('.carousel-content:gt('+(c)+')').prependTo( $slider.eq(2) );
// POPULATE WITH NAVIGATION BUTTONS
for(i=0;i<sliN;i++){
$('#nav-btns p').append(' '+ (i+1) +' ');
}
// TOGGLE ACTIVE CLASS TO NAV BUTTON
function navBtnsActive(){
c = c===-1 ? sliN-1 : c%sliN ; // counter resets
$('#nav-btns a').removeClass('btn-active').eq(c).addClass('btn-active'); // nav buttons actives
}
navBtnsActive();
var $lastCont;
function anim(){
if(c>m){ // right btn
$slider.animate({left:-w}, speed, 'linear', function(){
$(this).css({left:0}).find('.carousel-content:first').appendTo( $(this) );
});
m++;
}else if(c<m){ // left btn
$slider.animate({left:-w},0,function(){
$lastCont = $(this).find('.carousel-content:last');
$(this).find('.carousel-content:last').prependTo( $(this) );
}).animate({left:0}, speed, 'linear');
m--;
}
if(c!=m){anim();} // loop until match
}
// LEFT-RIGHT BUTTONS //
$btns.on('click',function(){
if(!$slider.is(':animated')){
var btnID = this.id=='btn-right' ? c++ : c-- ;
anim();
navBtnsActive();
m=c;
}
});
// NAV BUTTONS //
$('#nav-btns a').on('click',function(e){
e.preventDefault();
c = $(this).index();
anim();
navBtnsActive();
});
// AUTO SLIDE
function auto(){
clearInterval(intv);
intv = setInterval(function(){
$('#btn-right').click();
}, pause);
}
auto(); // start!
// PAUSE ON HOVER //
$('#gallery').on('mouseenter mouseleave',function( e ){
var mEnt = e.type=='mouseenter',
aSli = mEnt?clearInterval(intv):auto();
$btns.stop().fadeTo(300,mEnt?1:0);
});
});
HTML:
<div id="document_wrapper">
<div id="container">
<h1 class="title">BLOGUE</h1>
<div id="top-nav"></div>
<div id="gallery"> <!-- OUR PRECIOUS :) -->
<div class="carousel carousel-center">
<div class="carousel-slider">
<div class="carousel-content">
<!-- organize your content here -->
</div>
<!-- use more .carousel-content here -->
</div>
</div>
<div class="carousel carousel-left"></div>
<div class="carousel carousel-right"></div>
<div id="btn-left"></div>
<div id="btn-right"></div>
<div id="nav-btns"><p></p></div>
</div>
<!-- document content here -->
</div>
</div>
CSS:
*{margin:0;padding:0;} /* UGLY RESET */
body{
font:14px/24px "Myriad Pro","Trebuchet MS",sans-serif;
background:#F2EFED;
color:#555;
}
#document_wrapper{
position:relative;
overflow:hidden;
}
h1.title{
font-family:"Times New Roman",Times,serif;
font-size:14.16em;
line-height:0.6em;
font-weight:normal;
letter-spacing:10px;
color:#000;
position:relative;
z-index:1;
top:70px;
}
#container{
position:relative;
margin:0px auto;
width:980px;
padding-bottom:70px;
height:1000px;
background:#fff;
}
#top-nav{
border-top:1px solid #000;
position:relative;
z-index:2;
background:#fff;
height:36px;
width:100%;
}
/* GALLERY */
#gallery{
height:400px;
width:100%;
position:relative;
left:0px;
padding-bottom:36px; /* FOR NAV BUTTONS HEIGHT */
}
.carousel{
background:#147;
position:absolute;
margin-left:-10px;
width:850px;
height:400px;
border-left:10px solid #fff;
border-right:10px solid #fff;
overflow:hidden;
}
.carousel-left, .carousel-right{
opacity:0.2;
}
.carousel-left{
left:-860px;
}
.carousel-right{
left:860px;
}
.carousel-slider{
height:400px;
position:absolute;
left:0;
}
.carousel-content{
position:relative;
margin-left:-10px;
float:left;
width:850px;
height:400px;
border-left:10px solid #fff;
border-right:10px solid #fff;
}
/* BUTTONS */
#btn-left, #btn-right{
position:absolute;
background:#fff;
width:25px;
height:150px;
top:125px;
display:none;
cursor:pointer;
}
#btn-right{
right:130px;
}
/**/
#nav-btns{
position:relative;
top:400px;
height:30px;
width:850px;
}
#nav-btns{
text-align:right;
}
#nav-btns a{
font-style:italic;
text-decoration:none;
color:#888;
padding:0 8px;
margin:0 !important;
}
#nav-btns a.btn-active{
border-top:10px solid #fff;
text-decoration:none;
color:#000;
}
#nav-btns a:hover{
color:#000;
}
fiddle attached,
Minor code refactoring and optimisations can be done but the general idea is the same.
(function($) {
var $slider = $('#slider'),
finalOffset = '-' + $slider.children().last().offset().left + 'px';
slideSpeed = 5000,
timer = -1;
function startSlide() {
$slider.children().first().animate({
'margin-left' : finalOffset
}, slideSpeed, function() {
$slider.children().first().animate({'margin-left' : '0px'}, slideSpeed, function() {
startSlide();
});
});
}
startSlide();
}(jQuery));​
cheers

javascript onclick create(element) div viz popup box

I'm trying to make a pop up box, which gets invoked on clicking a button, this is what I've got so far.. http://jsfiddle.net/WGPhG/2/
Here is a fiddle that actually does what you want - http://jsfiddle.net/WGPhG/6/
JS
function popUp(){
var popup = document.createElement('div');
popup.className = 'popup';
popup.id = 'test';
var cancel = document.createElement('div');
cancel.className = 'cancel';
cancel.innerHTML = 'close';
cancel.onclick = function (e) { popup.parentNode.removeChild(popup) };
var message = document.createElement('span');
message.innerHTML = "This is a test message";
popup.appendChild(message);
popup.appendChild(cancel);
document.body.appendChild(popup);
}
NOTES
To set the class on an element you use element.className instead of element.class.
For the onclick event handler on the cancel element, it is better to directly assign the onclick handler with an anonymous function that does what you need as in my example above.
EDIT (More Efficient Way)
This is actually a much better of getting the results that you want because there is no overhead involved with recreating the elements every time the popup is shown. Fiddle - http://jsfiddle.net/WGPhG/7/
CSS
.popup
{
position:absolute;
top:0px;
left:0px;
margin:100px auto;
width:200px;
height:150px;
font-family:verdana;
font-size:13px;
padding:10px;
background-color:rgb(240,240,240);
border:2px solid grey;
z-index:100000000000000000;
display:none
}
.cancel
{
display:relative;
cursor:pointer;
margin:0;
float:right;
height:10px;
width:14px;
padding:0 0 5px 0;
background-color:red;
text-align:center;
font-weight:bold;
font-size:11px;
color:white;
border-radius:3px;
z-index:100000000000000000;
}
HTML
<button onClick="openPopup();">click here</button>
<div id="test" class="popup">
This is a test message
<div class="cancel" onclick="closePopup();"></div>
</div>
JS
function openPopup() {
document.getElementById('test').style.display = 'block';
}
function closePopup() {
document.getElementById('test').style.display = 'none';
}
Try this update on JSFiddle
Changed :
Center page (fixed).
effect (fadein and fadeout)
HTML
<button onClick="openPopup();">click here</button>
<div id="test" class="popup" style="display:none;">
This is a test message
<div class="cancel" onclick="closePopup();"></div>
</div>
CSS
.popup {
position:fixed;
top:0px;
left:0px;
bottom:0px;
right:0px;
margin:auto;
width:200px;
height:150px;
font-family:verdana;
font-size:13px;
padding:10px;
background-color:rgb(240,240,240);
border:2px solid grey;
z-index:100000000000000000;
}
.cancel {
display:relative;
cursor:pointer;
margin:0;
float:right;
height:10px;
width:14px;
padding:0 0 5px 0;
background-color:red;
text-align:center;
font-weight:bold;
font-size:11px;
color:white;
border-radius:3px;
z-index:100000000000000000;
}
.cancel:hover {
background:rgb(255,50,50);
}
JS
function openPopup() {
//document.getElementById('test').style.display = 'block';
$('#test').fadeIn(1000);
}
function closePopup() {
//document.getElementById('test').style.display = 'none';
$('#test').fadeOut(500);
}
Try This
function popUp(){
var popup = document.createElement('div');
popup.className = 'popup';
popup.id = 'test';
var cancel = document.createElement('div');
cancel.className = 'cancel';
cancel.setAttribute('onClick', 'document.getElementById("test").parentNode.removeChild('+popup +');')
popup.innerHTML = "This is a test message";
document.body.appendChild(popup);
popup.appendChild(cancel);
}
I've updated your Fiddle and made it work.
The changed HTML...
<button id="popupButton">click here</button>
Updated JavaScript...
document.onreadystatechange = function () {
function popUp() {
var popup = document.createElement('div');
popup.className = 'popup';
popup.id = 'test';
popup.innerHTML = "This is a test message";
var cancel = document.createElement('div');
cancel.className = 'cancel';
cancel.onclick= function () { popup.destroy(); }
popup.appendChild(cancel);
document.body.appendChild(popup);
}
document.getElementById('popupButton').onclick = popUp;
}​
Did this answer your question or is there anything else?
Update Improved the code and the fiddle. Now open and close works

Show / Hide / Toggle - Javascript / jQuery

I'm very new with Javascript.
I'm trying to do something with Show/Hide functions.
html:
<html>
<head>
<title> New Document </title>
<style>
#button01 {
width:100px;
height:50px;
margin:10px;
padding:6px 0 0 0;
background-color:#f0f0f0;
}
#button01:hover {
background-color:#ffcccc;
}
#button01 a {
display:block;
width:40px;
height:40px;
margin:auto;
background:url("button01.png")
}
#button01 a:hover {
width:40px;
height:40px;
background:url("button01-hover.png")
}
#hidden01 {
display:none;
width:300px;
height:200px;
margin:0 0 10px 0;
border:4px solid #ffcccc;
}
#button02 {
width:100px;
height:50px;
margin:10px;
padding:6px 0 0 0;
background-color:#f0f0f0;
}
#button02:hover {
background-color:#cccccc;
}
#button02 a {
display:block;
width:40px;
height:40px;
margin:auto;
background:url("button02.png")
}
#button02 a:hover {
width:40px;
height:40px;
background:url("button02-hover.png")
}
#hidden02 {
display:none;
width:300px;
height:200px;
margin:0 0 10px 0;
border:4px solid #cccccc;
}
</style>
</head>
<body>
<div style="width:300px;">
<div id="button01"></div>
<div id="button02"></div>
</div>
<div id="hidden01"> </div>
<div id="hidden02"> </div>
</body>
</html>
script:
function toggle(offset){
var i, x;
var stuff = Array('hidden01', 'hidden02'); //put all the id's of the divs here in order
for (i = 0; i < stuff.length; i++){ //hide all the divs
x = document.getElementById(stuff[i]);
x.style.display = "none";
}
// now make the target div visible
x = document.getElementById(stuff[offset]);
x.style.display = "block";
window.onload = function(){toggle(0);}
}
That's working, but I want to fix 2 things:
1- Close/Hide hidden divs if I click on it's corresponding button;
2- After clicking a button, fix hover button image. If click again unfix;
I've tried almost all the scripts posted and can not find a solution. I don't want to open the divs at same time.
If opens one, close the others.
You're using jQuery, so use jQuery.
$(function() {
function toggle(offset) {
$('div[id^=hidden]').hide().eq(offset).show();
}
toggle(0);
});
I don't know what you mean by the two things you want to fix, however. Please clarify.
Edit
Okay, I see what you're going for now. I've cleaned up your code a lot.
HTML
<div style="width:300px;">
<div id="button1"><a></a></div>
<div id="button2"><a></a></div>
</div>
<div id="hidden1"> </div>
<div id="hidden2"> </div>
CSS
#button1, #button2 {
width:100px;
height:50px;
margin:10px;
padding:6px 0 0 0;
background-color:#f0f0f0;
}
#button1:hover {
background-color:#fcc;
}
#button2:hover {
background-color:#ccc;
}
#button1 a, #button2 a {
display:block;
width:40px;
height:40px;
margin:auto;
}
#button1 a {
background:url(http://lorempixum.com/40/40?1)
}
#button2 a {
background:url(http://lorempixum.com/40/40?3)
}
#button1 a:hover, #button1.hover a {
background:url(http://lorempixum.com/40/40?2)
}
#button2 a:hover, #button2.hover a {
background:url(http://lorempixum.com/40/40?4)
}
#hidden1, #hidden2 {
display:none;
width:300px;
height:200px;
margin:0 0 10px 0;
border:4px solid #fcc;
}
JavaScript
var $buttons = $('div[id^=button]'),
$hiddenDivs = $('div[id^=hidden]'),
HOVER_CLASS = 'hover';
$buttons.live('click', function() {
var $this = $(this),
i = $this.index();
$buttons.removeClass(HOVER_CLASS);
$this.addClass(HOVER_CLASS);
$hiddenDivs.hide().eq(i).show();
}).first().click();
Demo
Last edit
Changed JavaScript and CSS. http://jsfiddle.net/mattball/bNCNQ/
CSS
#button1:hover a, #button1.hover a {
background:url(...)
}
#button2:hover a, #button2.hover a {
background:url(...)
}
JS
$buttons.live('click', function () {
var $this = $(this),
i = $this.index(),
show = !$this.hasClass(HOVER_CLASS);
$buttons.removeClass(HOVER_CLASS);
$this.toggleClass(HOVER_CLASS, show);
$hiddenDivs.hide().eq(i).toggle(show);
});
Here's a working demo: http://jsfiddle.net/R6vQ4/33/.
All of your JavaScript code can be condensed into this little block (and this isn't even as small as it can get):
$(document).ready(function()
{
$('div[id^=button]').click(function()
{
var element = $('#hidden' + $(this).attr('id').substr(6));
$('div[id^=button]').css('cssText', 'background-color: none');
if (element.is(':visible'))
{
$(this).css('cssText', 'background-color: none');
$('div[id^=hidden]').hide();
} else {
$('div[id^=hidden]').hide();
element.show();
$(this).css('cssText', 'background-color: ' + $(this).css('background-color') + ' !important');
}
});
});
The state of the button "sticks" when you press it, but my technique is a bit hacky, so feel free to change it.
When you use jQuery, you actually use it ;)

Categories