Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to do the overlay function.
function toggleOverlay(){
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('specialBox');
overlay.style.opacity = .8;
if(overlay.style.display == "block"){
overlay.style.display = "none";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
}
div#overlay {
display: none;
z-index: 2;
background: #000;
position: fixed;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
text-align: center;
}
div#specialBox {
display: none;
position: relative;
z-index: 3;
margin: 150px auto 0px auto;
width: 500px;
height: 300px;
background: #FFF;
color: #000;
}
div#wrapper {
position:absolute;
top: 0px;
left: 0px;
padding-left:24px;
}
<div id="overlay"></div>
<div id="specialBox">
<p>Special box content ...</p>
<button onmousedown="toggleOverlay()">Close Overlay</button>
</div>
<div id="wrapper">
<button onmousedown="toggleOverlay()">Apply Overlay</button>
</div>
In the current function, when i click the Apply overlay button the pop up is coming. But as per my requirement the pop up has to come when i execute the script i.e. without invoking the apply overlay button.
Please suggest me on this.
Thanks in advance.
Add this to your javascript AFTER the function
window.onload = function(){
toggleOverlay()
}
This invokes the functions when the page is loaded
Alternate option can be use self-invokling function
var publicObj = {};
(
publicObj.toggle = function togglefunction() {
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('specialBox');
overlay.style.opacity = .8;
if (overlay.style.display == "block") {
overlay.style.display = "none";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
})(publicObj);
function toggleOverlay(){
publicObj.toggle();
}
Fiddle
Related
I'm relatively new to Javascript, so I've pieced together the code I have by looking through the forums on here. However, I cannot get this to work, and I am needing help.
The desired end result I am trying to achieve is that whenever a user calls the moreInfo(ID) function, a modal pops up on the screen with the contents of the modal being populated from an external file that is built using PHP.
Right now, whenever I call the function, the modal pops up but does not display the external file. Instead, the modal displays the current page (??). A live version can be found here: http://classcolonies.com/app/test.php/
What am I doing wrong? How do I need to go about doing this instead? An explanation along with a solution would be ideal so I can learn and grow in my journey to understand javascript.
Launch Page (used to launch the modal)
<h1>Test Screen</h1><button onclick='moreInfo("12");'>Test</button>
<div id="infoModal" class="modal">
<div class="modal-window">
<span id="moreInfo"></span>
</div>
</div>
<script> /* AJAX name selector */
var infoModal = document.getElementById("infoModal");
function moreInfo(str){
if (window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest();}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("moreInfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","moreinfo.tem.php?assID=" + str, true);
xmlhttp.send();
infoModal.style.display = "block"; /* After fetching request, make modal appear */
}
window.onclick = function(event) { /* Make modal disappear when you click "X" */
if (event.target == infoModal) {infoModal.style.display = "none";}
}
</script>
<style>
.modal {
display: none;
position: fixed;
z-index: 20;
right: 0; top: 0;
width: 100%; height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.4);
-webkit-animation-name: fadeIn;
-webkit-animation-duration: 0.4s;
animation-name: fadeIn;
animation-duration: 0.4s}
/* Customized part listed below */
.modal-window{
display: grid;
position: fixed;
padding: 10px;
width: 600px; height: 350px;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
transition: height 0.5s;
grid-template-rows: 90px 1fr 60px;
grid-template-areas:
"top"
"content"
"controls";}
/* --------[TOP] -------- */
.modal-top {
display: grid;
grid-area: top;
border-bottom: 2px solid #5B7042;
grid-template-columns: 100px 1fr 80px;}
.pic{
display: inline-block;
width: 65px;
clip-path: circle();
margin-left: 10px;}
.modal-top .title {
display: flex;
align-items: center;
font-weight: 800;
font-size: 26px}
.due {
display: flex;
align-items: center;
font-size: 18px;
color: gray;}
/* --------[CONTENT] -------- */
.modal-content {
display: block;
grid-area: content;
overflow-y: scroll;
padding: 12px;}
.directions {
font-size: 18px;
line-height: 1.7}
textarea {
display: none;
width: 100%; height: 100px;
box-sizing: border-box;
font-size: 18px !important;
margin-top: 20px;}
/* --------[CONTROLS] -------- */
.modal-controls {
display: flex;
align-items: center;
grid-area: controls}
#askforhelp {margin-right: 10px;}
#sendmsg {display: none; margin-right: 10px}
#cancelmsg {display: none}
</style>
External file, used to replace the <span id="moreInfo"> with actual content
<div class='modal-top'>
<img class='pic' src='../resources/pics/1.png'>
<span class='title'> Reading Homework </span>
<span class='due'> Due 3d </span>
</div>
<div class="modal-content">
<div class='directions'>
<b>Directions:</b> You must complete the assignment to continue to the next section. Please type complete sentences and capitalization. Let me know if you need help.
</div>
<textarea placeholder='Type Question..'></textarea>
</div>
<div class="modal-controls">
<button id='askforhelp' class='button green-btn' onclick='askHelp("showform")'>Ask for Help</button>
<button id='markdone' class='button green-btn'>Mark as Done</button>
<button id='sendmsg' class='button green-btn'>Send Message</button>
<button id='cancelmsg' class='button grey-btn' onclick='askHelp("hideform")'>Cancel Message</button>
</div>
<script>
function askHelp(arg) {
var window = document.getElementsByClassName('modal-window')[0];
var textbox = document.getElementsByTagName("textarea")[0];
var helpBtn = document.getElementById('askforhelp');
var doneBtn = document.getElementById('markdone');
var sendBtn = document.getElementById('sendmsg');
var cancelBtn = document.getElementById('cancelmsg');
if (arg == "showform") {
window.style.height = '400px';
textbox.style.display = 'block';
helpBtn.style.display = 'none';
doneBtn.style.display = 'none';
sendBtn.style.display = 'block';
cancelBtn.style.display = 'block';
}
if (arg == "hideform") {
window.style.height = '350px';
textbox.style.display = 'none';
helpBtn.style.display = 'block';
doneBtn.style.display = 'block';
sendBtn.style.display = 'none';
cancelBtn.style.display = 'none';
}
}
</script>
Based on the answer by #Gil, Update your moreInfo function as below:
function moreInfo(str){
fetch("moreinfo.tem.php?assID=" + str).then((res) => res.text()).then(response=>{
document.getElementById("moreInfo").innerHTML=response;
infoModal.style.display = "block";
});
}
fetch returns a promise. From that promise, return the evaluated text from the response. This yields another promise which would contain the html or whatever.
It would be worth mentioning that the script in the returned html won't execute, so your askHelp function won't be defined. You can parse the html response and inject any script contents into the page as follow:
function moreInfo(str){
infoModal.style.display = "block";
fetch("moreinfo.tem.php?assID=" + str).then((response) =>response.text()).then((text) => {
var parser = new DOMParser();
var doc = parser.parseFromString(text, "text/html");
var ele = doc.documentElement;
var scripts = ele.getElementsByTagName('script');
for(var script of scripts){
var head = document.getElementsByTagName('head')[0];
var scriptElement = document.createElement('script');
scriptElement.setAttribute('type', 'text/javascript');
scriptElement.innerText = script.innerText;
head.appendChild(scriptElement);
head.removeChild(scriptElement);
}
document.getElementById("moreInfo").innerHTML=text;
});
}
fetch('xxx/com/api')
.then(responese=>responese.json())
.then(data=>{ do something..}
remember to add json() within first .then
Try using fetch instead.
Something like:
function moreInfo(str){
fetch("moreinfo.tem.php?assID=" + str).then((response) => {
response.text().then((text) => {
document.getElementById("moreInfo").innerHTML=text;
infoModal.style.display = "block";
});
})
}
Some explanation about the syntax here:
fetch makes an HTTP request to the URL provided (default is GET request, unless specified otherwise)
.then means, do something after the request is done.
(response) => {} is an arrow notation in JavaScript.
it's the same as writing function(response) {...}
I made a javascript banner which expands on rollover and close on click on a button. I cannot close it when the the banner is still expanding. When i click on the close button the banner expands and only after it starts to close. I thisnk it's about clear interval but but i dont't know how to resolve the problem. Can anyone help me?
var dagContainer = document.querySelector('.dag_sideslider');
var side_btn = document.querySelector('.side_btn');
var close_btn = document.querySelector('.dag_close');
side_btn.addEventListener("mouseover", open);
close_btn.addEventListener("click", closeBanner);
function open() {
side_btn.style.display = "none";
close_btn.style.display = "block";
var pos = 300;
var id = setInterval(frame, 5);
function frame() {
if (pos == 900) {
clearInterval(id);
} else {
pos++;
dagContainer.style.width = pos + 'px';
}
}
}
function closeBanner() {
close_btn.style.display = "block";
var idd = setInterval(framee, 5);
function framee() {
var poss = dagContainer.offsetWidth;
console.log(poss);
if (poss == 300) {
clearInterval(idd);
console.log("ss");
close_btn.style.display = "none";
side_btn.style.display = "block";
} else {
poss--;
console.log(poss)
dagContainer.style.width = poss + 'px';
console.log(poss);
}
}
}
.slideSider_container{
margin:0 auto 0;
position: relative;
width: 300px;
height: 600px;
}
.dag_sideslider{
background-color:#ea7900;
width: 300px;
height: 600px;
position: absolute;
right: 0;
top:0;
}
.side_btn{
width: 300px;
height: 600px;
}
.dag_close{
position: absolute;
top:0px;
right: 0px;
z-index:9999;
display: none
}
<div class="slideSider_container">
<div class="dag_sideslider" >
<div class="dag_close"><img src="close.png"></div>
<div class="side_btn"></div>
</div>
</div>
I am trying to make a transition with a div that should grow and overlap a text.
Here are my codes
const box = document.querySelector("#box");
const mybutt = document.querySelector("#mybutt");
mybutt.addEventListener("click", transitionfunction);
function transitionfunction() {
if(box.style.height != "100px"){
box.style.height = "100px";
box.style.transition = "2s";
}
else {
box.style.height = "50px";
box.style.transition = "2s";
}
}
#box {
background: red;
height: 50px;
width: 50px;
}
#para {
postion: fixed;
}
<div id="parentdiv">
<div id="box"></div>
<p id="para">Help</p>
</div>
<button id="mybutt">click</button>
At the moment, on the click of the button, both the button and the paragraph para move down, I want them to be fixed and I want the div, #box to cover the para but its not working. I tried putting it to fixed but doesnt work. And on the click on the button again, it should reveal the text again.
If you use position: fixed;, you should manually set the top property.
To make a div overlay some text, use z-index
const box = document.querySelector("#box");
const mybutt = document.querySelector("#mybutt");
mybutt.addEventListener("click", transitionfunction);
function transitionfunction() {
if (box.style.height != "100px"){
box.style.height = "100px";
box.style.transition = "2s";
} else {
box.style.height = "50px";
box.style.transition = "2s";
}
}
#mybutt {
position: fixed;
top: 120px;
}
#box {
background: red;
position: fixed;
height: 50px;
width: 50px;
z-index: 2;
}
#para {
position: fixed;
z-index: 1;
top: 60px;
}
<div id="parentdiv">
<div id="box"></div>
<p id="para">Help</p>
</div>
<button id="mybutt">click</button>
Firstly, you spelled "position" wrong for #para. Change it to:
#para {
position: absolute;
top: 10%;
}
This will keep the paragraph positioned in one spot; it won't move.
Fixed will work, although you might want to use 'absolute' instead if you want it to anchored to it's parent instead of the window itself.
Also, 'position' is misspelled; not sure if it is in your testing code.
The 'top' property has to be set for the element to know where to anchor itself, the 'position' property is what to anchor to.
HTML
<div id="parentdiv">
<div id="box"></div>
<p id="para">Help</p>
</div>
</div>
<button id="mybutt">click</button>
CSS
<style>
#box {
background: red;
height: 50px;
width: 50px;
}
#para {
position: absolute;
top:70;
}
</style>
*You also might want to move '#para' outside '#parentdiv', but it depends what you'll trying to ultimately do, it does work inside too.
Added:
To include an alert at 75px, you have to use a function that gives you more granular control(as far as I know at least). This is one solution:
<script>
const box = document.querySelector("#box");
const mybutt = document.querySelector("#mybutt");
mybutt.addEventListener("click", transitionfunction);
var intHeight = $("#box").css("height").split("p")[0];
function transitionfunction() {
if(intHeight < 100) {
intHeight++;
$("#box").css("height", intHeight + "px");
if (intHeight===76)
alert("75px!")
requestAnimationFrame(transitionfunction);
}
intHeight = $("#box").css("height").split("p")[0];
mybutt.addEventListener("click", revtransitionfunction);
mybutt.removeEventListener("click", transitionfunction);
}
function revtransitionfunction() {
if(intHeight >= 50) {
intHeight--;
$("#box").css("height", intHeight + "px");
if (intHeight===74)
alert("75px!")
requestAnimationFrame(revtransitionfunction);
}
intHeight = $("#box").css("height").split("p")[0];
mybutt.addEventListener("click", transitionfunction);
mybutt.removeEventListener("click", revtransitionfunction);
}
I'm trying to do a basic toggle clicking with js... I have this
<div id="box"></div>
<button id="btn"></button>
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
left: 50px;
}
js:
var btn = document.getElementById('btn');
var box = document.getElementById('box');
btn.addEventListener('click', function(){
if (box.style.left === '50px') {
box.style.left = '200px';
}
if (box.style.left === '200px') {
box.style.left = '50px';
}
});
I looked it up and this seems to be the method everyone uses for toggle clicking with pure js so I have no idea why it's not working for me, any ideas?
You should use the window.getComputedStyle instead (This way you will get the actual value of the style that applied to that element, and not just what's on the style attribute)..
You are missing an else there (otherwise you will always get the two if and nothing will change)
var btn = document.getElementById('btn');
var box = document.getElementById('box');
btn.addEventListener('click', function(){
if (window.getComputedStyle(box).left === '50px') {
box.style.left = '200px';
} else if (window.getComputedStyle(box).left === '200px') {
box.style.left = '50px';
}
});
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
left: 50px;
}
<div id="box"></div>
<button id="btn"></button>
#Dekel's answer already explains what was wrong with your code. However, you should work with classes instead. Not only is this way faster than retrieving window.getComputedStyle, it's also much easier
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var box = document.getElementById('box');
box.classList.toggle('left-50');
box.classList.toggle('left-200');
});
.left-50 {
left: 50px;
}
.left-200 {
left: 200px;
}
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
}
<div id="box" class="left-50"></div>
<button id="btn">bt</button>
Better use offset. Beside you are making a kind of toggle operation in here. Meanwhile, I modified your script to make it work:
<div id="box"></div>
<input type="button" id="btn" value=" Try it ">
<style>
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
left: 50px;
}
</style>
<script>
var btn = document.getElementById('btn');
var box = document.getElementById('box');
btn.addEventListener('click', function(){
if (box.offsetLeft == 50 ) {
box.style.left = 200 ;
}
else if (box.offsetLeft == 200 ) {
box.style.left = 50;
}
});
</script>
This question already has answers here:
getElementsByClassName not working [duplicate]
(2 answers)
Closed 6 years ago.
I've written a script, it's goal is to stop displaying images one and two, while allowing image 3 to remain displayed and move into their place. It works fine when I use div Id's instead of div Classes, but I would prefer to use div classes so I can group the elements like this:
function myFunction() {
var y = document.getElementsByClassName("firstimage secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
rather than this (in order to save space should I choose to include more elements):
function myFunction() {
var x = document.getElementById("firstimage");
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
var y = document.getElementById("secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
I thought that just changing the div id's to div classes, and the #imagenumber's to .imagenumber's (in addition to the change in the javascript I described above) would work but the script stops working when I do. I need the script to function in the same way that the code I am pasting below does, but with div classes instead of div Id's. Please tell me where I am going wrong.
CSS:
#firstimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: green;
margin-top:20px;
color: white;
}
#secondimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: blue;
margin-top:20px;
color: white;
}
#thirdimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: red;
margin-top:20px;
color: white;
}
HTML:
<button onclick="myFunction()">Try me</button>
<div id="firstimage">
DIV element.
</div>
<div id="secondimage">
A second DIV element.
</div>
<div id="thirdimage">
A third DIV element.
</div>
Javascript:
function myFunction() {
var x = document.getElementById("firstimage");
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
var y = document.getElementById("secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
document.getElementsByClassName returns an array of elements, so you would need to iterate through that array and operate on each element within that loop.
You should use getElementsByClassName() or querySelectorAll() to collect all div.Klass (Klass being an arbitrary name). The following Snippet uses querySelectorAll() details are commented in source.
SNIPPET
function toggleDiv() {
// Collect all .image into a NodeList
var xs = document.querySelectorAll(".image");
// Declare i and qty for "for" loop
var i, qty = xs.length;
// Use "for" loop to iterate through NodeList
for (i = 0; i < qty; i++) {
// If this div.image at index [i] is "none"...
if (xs[i].style.display === 'none') {
// then make it "block"...
xs[i].style.display = 'block';
} else {
// otherwise set display to "none"
xs[i].style.display = 'none';
}
}
}
#firstimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: green;
margin-top: 20px;
color: white;
}
#secondimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: blue;
margin-top: 20px;
color: white;
}
#thirdimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: red;
margin-top: 20px;
color: white;
}
<button onclick="toggleDiv()">Try me</button>
<div id="firstimage" class='image'>
DIV element.
</div>
<div id="secondimage" class='image'>
A second DIV element.
</div>
<div id="thirdimage" class='img'>
A third DIV element.
</div>
In this function, just using an "array-like" object such as a NodeList demonstrated in the Snippet above. An array would be used in the same manner as it is in the Snippet. Should you want to do more advanced processing of the divs such as running a function on each of them and returned then converting an "array-like" object into an array would be necessary to run methods like map, forEach, slice, etc.