Add style with JavaScript - javascript

I am trying to set CSS styles using Javascript.
I have written this code:
<div class="dim" id="dim" title="Event">
</div>
<div class="dialog_wrapper" id="dialog_wrapper">
<div class="dialog" id="dialog"><img id="buyukresim" src="http://ginger-mum.com/wp-content/uploads/2015/10/3633-1269758855-0da5042c33400a811a5d766be4579cb8.jpg" height="250"></div>
</div>
<script>
document.getElementById('buyukresim').style.display = "none";
document.getElementById('dim').style.display = "none";
document.getElementById('dialog_wrapper').style.display = "none";
document.getElementById('dialog').style.display = "none";
function karanlikyap2() {
var ogedim = document.getElementById('dim');
var ogewrapper = document.getElementById('dialog_wrapper');
var ogedialog = document.getElementById('dialog');
var ogeresim = document.getElementById('buyukresim');
ogedim.style.height = "100%";
ogedim.style.width = "100%";
ogedim.style.position = "fixed";
ogedim.style.left = "0";
ogedim.style.top = "0";
ogedim.style.z-index = "1 !important";
ogedim.style.background-color = "black";
ogedim.style.filter = "alpha(opacity=75)";
ogedim.style.-khtml-opacity = "0.75";
ogedim.style.-moz-opacity = "0.75";
ogedim.style.opacity = "0.75";
ogedim.style.display = "block";
ogewrapper.style.width = "100%";
ogewrapper.style.top = "0";
ogewrapper.style.left = "0";
ogewrapper.style.position = "absolute";
ogewrapper.style.z-index = "5";
ogewrapper.style.display = "block";
ogedialog.style.width = "400";
ogedialog.style.height = "400";
ogedialog.style.margin = "0 auto";
ogedialog.style.padding = "40";
ogedialog.style.background-color = "#fff";
ogedialog.style.border = "1px solid #ccc";
ogedialog.style.color = "#333";
ogedialog.style.display = "block";
ogeresim.style.display = "block";
}
</script>
<button onclick="karanlikyap2()">Karanlık 2</button>
But the code is not working.
Note : I have a good French, but my English isn't good. Pardon me. I hope you understand.

What you are doing to alter the CSS is not a good way. Please look for references over the internet. In JS, it doesn't normally work the way you expect it to work. You are trying to change the CSS like you would normally do with CSS, but JS is a bit picky when it comes to CSS. For example to change background color, in CSS you would write "background-color", but in JS "background-color" would be "backgroundColor".
Only change the CSS from JS if absolutely necessary, use CSS class to style your element.
You can reference https://www.kirupa.com/html5/setting_css_styles_using_javascript.htm
But if you really want to do it this way, here it is how:
<div class="dim" id="dim" title="Event">
</div>
<div class="dialog_wrapper" id="dialog_wrapper">
<div class="dialog" id="dialog"><img id="buyukresim" src="http://ginger-mum.com/wp-content/uploads/2015/10/3633-1269758855-0da5042c33400a811a5d766be4579cb8.jpg" height="250"></div>
</div>
<button onclick="karanlikyap2()">Karanlık 2</button>
<script>
document.getElementById('buyukresim').style.display = "none";
document.getElementById('dim').style.display = "none";
document.getElementById('dialog_wrapper').style.display = "none";
document.getElementById('dialog').style.display = "none";
function karanlikyap2() {
var ogedim = document.getElementById('dim');
var ogewrapper = document.getElementById('dialog_wrapper');
var ogedialog = document.getElementById('dialog');
var ogeresim = document.getElementById('buyukresim');
ogedim.style.height = "100px";
ogedim.style.width = "100px";
ogedim.style.position = "fixed";
ogedim.style.left = "0";
ogedim.style.top = "0";
ogedim.style['z-index'] = "1 !important";
ogedim.style['background-color'] = "black";
ogedim.style.filter = "alpha(opacity=75)";
ogedim.style['-khtml-opacity'] = "0.75";
ogedim.style['-moz-opacity'] = "0.75";
ogedim.style.opacity = "0.75";
ogedim.style.display = "block";
ogewrapper.style.width = "100%";
ogewrapper.style.top = "0";
ogewrapper.style.left = "0";
ogewrapper.style.position = "absolute";
ogewrapper.style['z-index'] = "5";
ogewrapper.style.display = "block";
ogedialog.style.width = "400";
ogedialog.style.height = "400";
ogedialog.style.margin = "0 auto";
ogedialog.style.padding = "40";
ogedialog.style['background-color'] = "#fff";
ogedialog.style.border = "1px solid #ccc";
ogedialog.style.color = "#333";
ogedialog.style.display = "block";
ogeresim.style.display = "block";
}
</script>

As gavgrif hinted at in the comments, it would be better to define static CSS styles and then manipulate the class names instead of trying to set everything with JS. Only setting things at run-time when they need to be dynamic and changeable. This will help with the separation of concerns and help make your code more maintainable.
In this case everything you are defining is static, the only real change you are making is hiding or showing the elements via changing display to none or block. You can easily achieve a similar effect by instead just defining them as blocks and creating a class that hides an element via visibility: hidden. Then you can hide and show them by adding or removing that new class.
This is how I would rewrite it:
function karanlikyap2() {
var ogedim = document.getElementById('dim');
var ogewrapper = document.getElementById('dialog_wrapper');
// you only need to remove the hidden class from the items at the top
// level of the DOM, the wrapper and dim
ogedim.classList.remove('hidden');
ogewrapper.classList.remove('hidden');
}
function hide() {
var ogedim = document.getElementById('dim');
var ogewrapper = document.getElementById('dialog_wrapper');
// add the hidden class back on to hide them again.
ogedim.classList.add('hidden');
ogewrapper.classList.add('hidden');
}
// hide the dialog when something is clicked
document.getElementById('dialog_wrapper').addEventListener('click', hide, false);
document.getElementById('dim').addEventListener('click', hide, false);
#dim {
height: 100%;
width: 100%;
position: fixed;
left: 0;
top: 0;
z-index: 1 !important;
background-color: black;
filter: alpha(opacity=75);
-khtml-opacity: 0.75;
-moz-opacity: 0.75;
opacity: 0.75;
display: block;
}
#dialog_wrapper {
width: 100%;
top: 0;
left: 0;
position: absolute;
z-index: 5;
display: block;
}
#dialog {
width: 400px;
height: 400px;
margin: 0 auto;
padding: 40px;
background-color: #fff;
border: 1px solid #ccc;
color: #333;
display: block;
}
.hidden {
visibility: hidden;
}
<div class="dim hidden" id="dim" title="Event">
</div>
<div class="dialog_wrapper hidden" id="dialog_wrapper">
<div class="dialog" id="dialog">
<img id="buyukresim" src="https://lorempixel.com/output/cats-q-c-250-250-4.jpg" height="250">
</div>
</div>
<button onclick="karanlikyap2()">Karanlık 2</button>
(I've used a different image to get around mixed-content issues because StackOverflow is served over https and your image is on http.)
Further reading:
more information about classList
Séparation du fond et de la forme

Related

transition : resize a div before to display image

I wonder me if it's possible in css / pure JS to display an image after that the container has reaches it's size after a transition...
Now the image is displayed before the transition, so sometimes the image is overlapping the container!
Here's what I done so far...
Is there a simplest way to resize images?
What about resizing if I don't specify the width and height of the image?
I'm lost in translation, so if you have a different approach it will be more than appreciate!
Thanks to you folks and have a nice day!!!
function resizePopupToH800(){
let popup = document.getElementById("popup");
popup.style.width="800px";
popup.style.height="600px";
popup.style.marginLeft="-400px";
popup.style.marginBottom="-300px";
setImage("https://dummyimage.com/700x500/c9c9c9/fff","big image");
}
function resizePopupToV400(){
let popup = document.getElementById("popup");
popup.style.width="400px";
popup.style.height="550px";
popup.style.marginLeft="-200px";
popup.style.marginBottom="-275px";
setImage("https://dummyimage.com/300x400/c9c9c9/fff","vertical");
}
function resizePopupToSQ500(){
let popup = document.getElementById("popup");
popup.style.width="500px";
popup.style.height="500px";
popup.style.marginLeft="-250px";
popup.style.marginBottom="-250px";
setImage("https://dummyimage.com/400x400/c9c9c9/fff","autoportrait");
}
function resizePopupToSQ300(){
let popup = document.getElementById("popup");
popup.style.width="300px";
popup.style.height="300px";
popup.style.marginLeft="-150px";
popup.style.marginBottom="-150px"; setImage("https://dummyimage.com/200x200/c9c9c9/fff","autoportrait");
}
function resizePopupToH550(){
let popup = document.getElementById("popup");
popup.style.width="550px";
popup.style.height="400px";
popup.style.marginLeft="-275px";
popup.style.marginBottom="-200px";
setImage("https://dummyimage.com/475x300/c9c9c9/fff","horizontal");
}
function setImage(url,text){
openPopup();
let imageRessource = url;
let legend = document.getElementById("popupTitleDiv");
let img = document.getElementById("popupImage");
img.src = imageRessource;
legend.innerHTML = text;
}
function addListeners(){
let resizerH = document.getElementById("resizerH800");
resizerH.addEventListener("click", resizePopupToH800);
let resizerV = document.getElementById("resizerV400");
resizerV.addEventListener("click", resizePopupToV400);
let resizerSQ = document.getElementById("resizerSQ500");
resizerSQ.addEventListener("click", resizePopupToSQ500);
let resizerSQ3 = document.getElementById("resizerSQ300");
resizerSQ3.addEventListener("click", resizePopupToSQ300);
let resizerHL = document.getElementById("resizerH550");
resizerHL.addEventListener("click", resizePopupToH550);
let popup= document.getElementById("popup");
popup.addEventListener("click", closePopup);
let pop= document.getElementById("openPop");
pop.addEventListener("click", openPopup);
}
function closePopup(){
let popup= document.getElementById("popup");
popup.style.display = "none";
}
function openPopup(){
let popup= document.getElementById("popup");
popup.style.display = "grid";
}
#test p{
cursor:pointer;
}
/* popup classes */
*{
box-sizing: border-box;
}
#popup{
display:grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows:20px auto 20px;
gap:20px;
position:absolute;
color:#ffffff;
width:500px;
height:500px;
opacity:1;
background-color: #666666;
z-index:3;
padding:10px;
left:50%;
margin-left:-250px;
bottom:50%;
margin-bottom:-250px;
cursor:pointer;
border:1px solid #ffffff;
transition:0.5s;
}
#popupTitleDiv{
grid-column-start:1;
grid-column-end:3;
}
#popupImageDiv{
position:static;
grid-column-start:1;
grid-column-end:3;
margin-top:auto;
margin-bottom:auto;
text-align:center;
}
#popupFooterDiv{
grid-column-start:1;
grid-column-end:3;
text-align:right;
}
/* popup classes */
<body onLoad="addListeners()">
<div id="popup">
<div id="popupTitleDiv">brume</div>
<div id="popupImageDiv">
<img id="popupImage" src="http://pirson.me/cv/brume.jpg" alt="photo Nicolas Pirson">
</div>
<div id="popupFooterDiv">©2022</div>
</div>
<div id="test">
<p id="openPop"><b>openGalery</b></p>
<p id="resizerH800">resize to 800 x 600 (large)</p>
<p id="resizerV400">resize to 400 x 550 (verical)</p>
<p id="resizerSQ500">resize to 500 x 500 (square)</p>
<p id="resizerSQ300">resize to 300 x 300 (square)</p>
<p id="resizerH550">resize to 550 x 400 (horizontal)</p>
</div>
</body>
[EDIT] :
The only turnaround I found at this moment is to display a 1px x 1px image during the transition, then display the image with setTimeOut but it's tricky AMO...
function setImage(url,text){
openPopup();
let imageRessource = url;
let legend = document.getElementById("popupTitleDiv");
let img = document.getElementById("popupImage");
img.src = "https://dummyimage.com/1x1/c9c9c9/fff";
legend.innerHTML = text;
let timeOut = setTimeout(displayImage,1000,imageRessource);
}
function displayImage(img){
let myimg = document.getElementById("popupImage");
myimg.src = img;
}
So there's no image visible during the transition So I changed my transition to : transition:2s; to get a smoother effect.
Any better suggestion if possible?
Thanks.
Nicolas.

Javascript : add images in div upon selecting value from select box

I am trying too add image inside dynamically created div. When user create go button it should create div element and image inside it according to value selected in select box. I have created div tag dynamically and created image object in order to get image. but in my code image is not loading inside div. can anyone help me to figure out issue ?
CSS
<style>
body{
background-image: url("final_images/back.jpg");
}
.container{
/*width: 600px;*/
/*height: 200px;*/
border:inset;
margin-top: 100px;
margin-left: 300px;
margin-right: 190px;
background-color:rgba(255, 234, 134, 0.9);
}
#selectBox{
margin-left: 210px;
width: 160px;
}
#holder {
width: 300px;
height: 300px;
background-color: #ffffff;
}
</style>
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class = 'container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
<option value="womens">Women's coat</option>
<option value="mens">Men's coat</option>
<option value="kids">Kid's toys</option>
<option value="mixture">Classic mixture</option>
<option value="earing">Gold Earing</option>
</select>
<INPUT TYPE="button" VALUE="Go" id="go">
</INPUT>
</form>
<HR size="4" color="red" id="hr">
<!-- <div id="holder"> </div> -->
</div>
</body>
</html>
Javascript
<script>
imageObj = new Image(128, 128);
// set image list
images = new Array();
images[0]="final_images/wcoat.jpg";
images[1]="final_images/wcoat.jpg";
var go = document.getElementById('go');
go.addEventListener("click", loadItem);
function loadItem() {
var mainDiv = document.getElementById("main");
var btnPre = document.createElement("input");
//Assign different attributes to the element.
btnPre.type = "button";
btnPre.value = "previous";
btnPre.id = "preBtn";
mainDiv.appendChild(btnPre);
newdiv = document.createElement('div'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv); //add an id
var btnNxt = document.createElement("input");
//Assign different attributes to the element.
btnNxt.type = "button";
btnNxt.value = "next";
btnNxt.id = "nxtBtn";
mainDiv.appendChild(btnNxt);
var holder = document.getElementById("holder");
if(document.getElementById('selectBox').value == "womens"){
holder.src = images[0] + " Women's coat";
}
else if(document.getElementById('selectBox').value == "mens"){
holder.src = images[1] + " Men's coat";
}
}
</script>
A div is not an image container. Replace with img in the createElement fixes this.
Another big problem is the margins you use.
I've made a few adjustments
replaced margin-left with float: right for the select
put margin auto for left and right on the box.
imageObj = new Image(128, 128);
// set image list
images = new Array();
images[0] = "final_images/wcoat.jpg";
images[1] = "final_images/wcoat.jpg";
var go = document.getElementById('go');
go.addEventListener("click", loadItem);
function loadItem() {
var mainDiv = document.getElementById("main");
var btnPre = document.createElement("input");
//Assign different attributes to the element.
btnPre.type = "button";
btnPre.value = "previous";
btnPre.id = "preBtn";
mainDiv.appendChild(btnPre);
newdiv = document.createElement('img'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv); //add an id
var btnNxt = document.createElement("input");
//Assign different attributes to the element.
btnNxt.type = "button";
btnNxt.value = "next";
btnNxt.id = "nxtBtn";
mainDiv.appendChild(btnNxt);
var holder = document.getElementById("holder");
if (document.getElementById('selectBox').value == "womens") {
holder.src = images[0] + " Women's coat";
} else if (document.getElementById('selectBox').value == "mens") {
holder.src = images[1] + " Men's coat";
}
}
body {
background-image: url("final_images/back.jpg");
}
* {
box-sizing: border-box;
}
.container {
width: 400px;
border: inset;
margin-top: 100px;
margin-left: auto;
margin-right: auto;
background-color: rgba(255, 234, 134, 0.9);
}
#selectBox {
float: right;
width: 160px;
}
#holder {
width: 300px;
height: 300px;
background-color: #ffffff;
}
<div class='container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
<option value="womens">Women's coat</option>
<option value="mens">Men's coat</option>
<option value="kids">Kid's toys</option>
<option value="mixture">Classic mixture</option>
<option value="earing">Gold Earing</option>
</select>
<INPUT TYPE="button" VALUE="Go" id="go">
</INPUT>
</form>
<HR size="4" color="red" id="hr" />
<!-- <div id="holder"> </div> -->
</div>
You need to use an image tag instead of a div. You could also load images with CSS but thats probably not what you want.
starting on this line:
var holder = document.getElementById("holder");
var image = new Image(128, 128);
if (document.getElementById('selectBox').value == "womens") {
image.src = images[0];
holder.appendChild(image);
holder.appendChild(document.createTextNode(" Women's coat"));
} else if (document.getElementById('selectBox').value == "mens") {
image.src = images[1];
holder.appendChild(image);
holder.appendChild(document.createTextNode(" Men's coat"));
}
Let me elaborate.
In the JavaScript code you are creating a div element here
newdiv = document.createElement('div'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv);
and then you are searching for element with Id holder and setting new image url.
var holder = document.getElementById("holder");
// holder is <div></div> element
if (document.getElementById('selectBox').value == "womens") {
holder.src = images[0] + " Women's coat";
} else if (document.getElementById('selectBox').value == "mens") {
holder.src = images[1] + " Men's coat";
}
holder is a div tag now. it has no src attribute
But div element do not have attribute with name src. so the above code will just add one more attribute to your div tag. but browser will not interpret it.
So if you want load image by setting src attribute, then you probably have to create holder as img tag which has attribute src. like this.
newdiv = document.createElement('img'); //create a img
newdiv.id = 'holder';
mainDiv.appendChild(newdiv);
holder is a img tag. now it has src attribute
now it will work with no problem.

How to close custom made prompt box in javascript?

I'm trying to make a custom prompt box in javascript. However, I just can't figure out how to close it again. The cancel button does work (the prompt box disappears), but when you click on the ok button, the box doesn't disappear.
Since I based my code on the code on this page: https://www.developphp.com/video/JavaScript/Custom-Prompt-Box-Programming-Tutorial
But now I see that if I copy the example on that page, the OK button doesn't work either. Can someone tell me what's wrong?
This is the example on the site I linked to, which doesn't work:
<!DOCTYPE html>
<html>
<head>
<style>
#dialogoverlay{
display: none;
opacity: .8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display: none;
position: fixed;
background: #000;
border-radius:7px;
width:550px;
z-index: 10;
}
#dialogbox > div{ background:#FFF; margin:8px; }
#dialogbox > div > #dialogboxhead{ background: #666; font-size:19px; padding:10px; color:#CCC; }
#dialogbox > div > #dialogboxbody{ background:#333; padding:20px; color:#FFF; }
#dialogbox > div > #dialogboxfoot{ background: #666; padding:10px; text-align:right; }
</style>
<script>
function changeText(val){
document.getElementById('status').innerHTML = val;
}
function doStuff(val){
document.body.style.background = val;
}
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "Acknowledge This Message";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">OK</button>';
}
this.ok = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
function CustomConfirm(){
this.render = function(dialog,op,id){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "Confirm that action";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Confirm.yes(\''+op+'\',\''+id+'\')">Yes</button> <button onclick="Confirm.no()">No</button>';
}
this.no = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
this.yes = function(op,id){
if(op == "delete_post"){
deletePost(id);
}
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Confirm = new CustomConfirm();
function CustomPrompt(){
this.render = function(dialog,func){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "A value is required";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxbody').innerHTML += '<br><input id="prompt_value1">';
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Prompt.ok(\''+func+'\')">OK</button> <button onclick="Prompt.cancel()">Cancel</button>';
}
this.cancel = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
this.ok = function(func){
var prompt_value1 = document.getElementById('prompt_value1').value;
window[func](prompt_value1);
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Prompt = new CustomPrompt();
</script>
</head>
<body>
<div id="dialogoverlay"></div>
<div id="dialogbox">
<div>
<div id="dialogboxhead"></div>
<div id="dialogboxbody"></div>
<div id="dialogboxfoot"></div>
</div>
</div>
<h1>My web document content ...</h1>
<h2>My web document content ...</h2>
<button onclick="alert('You look very pretty today.')">Default Alert</button>
<button onclick="Alert.render('You look very pretty today.')">Custom Alert</button>
<button onclick="Prompt.render('And you also smell very nice.')">Custom Alert 2</button>
<h3>My web document content ...</h3>
</body>
</html>
You're missing the second parameter for the ok button click, which allows you to invoke a function once you click ok:
<button onclick="Prompt.render('And you also smell very nice.', 'doStuff')">Custom Alert 2</button>
This will invoke doStuff with the value from the prompt.
There is one possibility check with the id's used for elements in you the code provided if at all there are duplicate id the javaScript will not work properly.
This statement in the code,
document.getElementById('dialogbox').style.display = "none";
Is making use of element with id 'dialogbox' so if at all there is another element in your page having same id. your code will not work properly. More help can be provided if there is code with problem is shared.

Creating popup boxes using html css and javascript

basically i'm trying to create multiple popup boxes that appear when different links are clicked. For some reason, a popup box only appears when the first link is clicked. When the rest of the links are clicked, nothing happens. Any help is appreciated, thanks. Also, I've only included 2 of the links in this example.
javascript code:
function xpopup() {
document.getElementById("x").onclick= function(){
var overlay = document.getElementById("overLay");
var popup = document.getElementById("xPopup");
overlay.style.display = "block";
popup.style.display = "block";
}
}
function ypopup() {
document.getElementById("y").onclick= function(){
var overlay = document.getElementById("overLay");
var popup = document.getElementById("yPopup");
overlay.style.display = "block";
popup1.style.display = "block";
}
}
</script>
HTML code:
<body onLoad="xpopup()"; "ypopup()";>
<div id="overLay"></div>
<div class="popupBox" id="xPopup"></div>
<div class="popupBox" id="yPopup"></div>
Link 1<br>
Link 2<br>
CSS code:
.popupBox{
display:none;
position: fixed;
width: 30%;
height: 40%;
margin-left: 16.5%;
margin-top: 4.5%;
background-color: white;
border: 2px solid black;
border-radius: 10px;
z-index: 10;
}
#overLay{
display:none;
position: fixed;
width: 100%;
height: 100%;
background-color: #707070;
opacity: 0.7;
z-index: 9;
left: 0;
top: 0;
}
Replace <body onLoad="xpopup()"; "ypopup()";> with <body onLoad="xpopup(); ypopup();"> and in your JavaScript code you have a typo.
function ypopup() {
document.getElementById("y").onclick= function(){
var overlay = document.getElementById("overLay");
var popup = document.getElementById("yPopup");
overlay.style.display = "block";
popup1.style.display = "block"; // Here the popup1 is undefined change it to popup.style.....
}
}
Edit :-->
I've changed your code to hide the popup, if you click on the greyed out section.
Fiddle
HTML:
<body>
<div id="overLay"></div>
<div class="popupBox" id="xPopup"></div>
<div class="popupBox" id="yPopup"></div>
Link 1
<br />
Link 2
<br />
</body>
JavaScript:
var overlay = document.getElementById("overLay");
var xpopup = document.getElementById("xPopup");
var ypopup = document.getElementById("yPopup");
document.getElementById("x").onclick = function () {
overlay.style.display = "block";
xpopup.style.display = "block";
};
document.getElementById("y").onclick = function () {
overlay.style.display = "block";
ypopup.style.display = "block";
};
overlay.onclick = function () {
overlay.style.display = "none";
xpopup.style.display = "none";
ypopup.style.display = "none";
};
I'm seeing two issues --
The first is already answered by chipChocolate.py:
Replace <body onLoad="xpopup()"; "ypopup()";> with <body onLoad="xpopup(); ypopup();">.
The second (and maybe this is just a typo?) is that you have:
function ypopup() {
document.getElementById("y").onclick= function()
var overlay = document.getElementById("overLay");
var popup = document.getElementById("yPopup");
overlay.style.display = "block";
popup1.style.display = "block";
}
}
You're referencing popup1 but you've named your variable popup. If you open up the javascript console you'll probably see that's throwing an error. Rename the variable popup1 and this should work.

How can I change the x position of a div via javascript when I click on another div this way?

<body>
<div id = "SiteContainer">
<div id = "NavigationButtons"></div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition();">x</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition();">y</div>
<div id = "VideoWrapper">
<div id = "SlideShowItem">
<img src="Images/A.png" alt="A"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/B.png" alt="B"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/C.png" alt="C" ></img>
</div>
</div>
</div>
</div>
<script>
var wrapper = document.querySelector("#VideoWrapper");
function setPosition(e)
{
if(e.target.name = "forward")
{
if!(wrapper.style.left = "-200%")
{
wrapper.style.left = wrapper.style.left - 100%;
}
}
else
{
if(e.target.name = "back")
{
if!(wrapper.style.left = "0%")
{
wrapper.style.left = wrapper.style.left + 100%;
}
}
}
}
</script>
</body>
Hi, I am very new to javascript. What I am trying to do, is change the x-position of a div when another div (NavigationForward or NavigationBackward) is clicked. However it does not appear to do anything at all. Basically if the div with name forward is clicked, I want to translate the VideoWrapper -100% from it's current position and +100% when "back". The css div itself VideoWrapper has a width of 300%. Inside this div as you can see is a SlideShowItem which is what will change. Perhaps I am adding and subtracting 100% the wrong way?
EDIT:
Thanks everyone for helping me out with this...I had just one more query, I am trying to hide the arrows based on whether the wrapper is at the first slide or the last slide. If its on the first slide, then I'd hide the left arrow div and if it's on the last, I'd hide the right arrow, otherwise display both of em. Ive tried several ways to achieve this, but none of em work, so Ive resorted to using copies of variables from the function that works. Even then it does not work. It appears that my if and else if statements always evaluate to false, so perhaps I am not retrieving the position properly?
function HideArrows()
{
var wrapper2 = document.getElementById("VideoWrapper");
var offset_x2 = wrapper2.style.left;
if(parseInt(offset_x2,10) == max_x)
{
document.getElementById("NavigationForward").display = 'none';
}
else if(parseInt(offset_x2,10) == min_x)
{
document.getElementById("NavigationBackward").display = 'none';
}
else
{
document.getElementById("NavigationForward").display = 'inline-block';
document.getElementById("NavigationBackward").display = 'inline-block';
}
}
//html is the same except that I added a mouseover = "HideArrows();"
<div id = "ShowReelContainer" onmouseover="HideArrows();">
To achieve this type o slider functionality your div VideoWrapper must have overflow:hidden style, and your SlideShowItemdivs must have a position:relative style.
Then to move the slides forward or backward you can use the style left which allows you to move the divs SlideShowItem relative to it's parent VideoWrapper.
I've tested this here on JSFiddle.
It seems to work as you described in your question, although you may need to do some adjustments, like defining the width of your slides, how many they are and so on.
For the sake of simplicity, I defined them as "constants" on the top of the code, but I think you can work from that point on.
CSS
#VideoWrapper{
position:relative; height:100px; white-space:nowrap;width:500px;
margin-left:0px; border:1px solid #000; overflow:hidden; }
.SlideShowItem{
width:500px; height:100px;display:inline-block;position:relative; }
#NavigationForward, #NavigationBackward{
cursor:pointer;float:left; background-color:silver;margin-right:5px;
margin-bottom:10px; text-align:center; padding:10px; }
HTML
<div id = "SiteContainer">
<div id = "NavigationButtons">
</div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition('back');">prev</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition('forward');">next</div>
<div style="clear:both;"></div>
<div id = "VideoWrapper">
<div class= "SlideShowItem" style="background-color:blue;">
Slide 1
</div>
<div class = "SlideShowItem" style="background-color:yellow;">
Slide 2
</div>
<div class = "SlideShowItem" style="background-color:pink;">
Slide 3
</div>
</div>
</div>
</div>
JavaScript
var unit = 'px'; var margin = 4; var itemSize = 500 + margin; var itemCount = 3; var min_x = 0; var max_x = -(itemCount-1) * itemSize;
function setPosition(e) {
var wrapper = document.getElementById("VideoWrapper");
var slides = wrapper.getElementsByTagName('div');
var offset_x = slides[0].style.left.replace(unit, '');
var curr_x = parseInt(offset_x.length == 0 ? 0 : offset_x);
if(e == "forward")
{
if(curr_x <= max_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + -itemSize) + unit;
}
else if(e == "back")
{
if(curr_x >= min_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + itemSize) + unit;
} }
After you analyze and test the code, I don't really know what's your purpose with this, I mean, you maybe just playing around or trying to develop something for a personal project, but if you are looking for something more professional avoid to create things like sliders on your own, as there are tons of plugins like this available and well tested out there on the web.
Consider using jQuery with NivoSlider, it works like a charm and is cross browser.
I would recommend using jQuery, this will reduce your coding by quite a bit. Can read more here: http://api.jquery.com/animate/
I've created a simple fiddle for you to take a look at. This example uses the .animate() method to reposition two div elements based on the CSS 'left' property.
CSS:
#container {
position: absolute;
left: 1em;
top: 1em;
right: 1em;
bottom: 1em;
overflow: hidden;
}
#one, #two {
position: absolute;
color: white;
}
#one {
background: pink;
width: 100%;
top:0;
bottom:0;
}
#two {
background: blue;
width: 100%;
left: 100%;
top:0;
bottom:0;
}
HTML:
<div id="container">
<div id="one">Div One</div>
<div id="two">Div Two</div>
</div>
JavaScript/jQuery:
var one, two, container;
function animateSlides(){
one.animate({
left : '-100%'
}, 1000, function(){
one.animate({
left : 0
}, 1000);
});
two.animate({
left : 0
}, 1000, function(){
two.animate({
left:'100%'
}, 1000);
});
};
$(function(){
one = $('#one');
two = $('#two');
container = $('#container');
setInterval(animateSlides, 2000);
});
JSFiddle Example: http://jsfiddle.net/adamfullen/vSSK8/3/

Categories

Resources