I'm trying for hours now to add a wrapper around two divs (aside and .related) at a certain screensize (>60em and <90em). I'm doing this with matchMedia and an eventListener. The wrapper seems to be added at the right spot, but the problem is that it's still there even when the condition of the size is not met.
Here is a jsfiddle: http://jsfiddle.net/Vanilla__/4q26ngmg/1/
Simplified HTML:
<body>
<header>Header</header>
<main>Main</main>
<aside>Aside</aside>
<div class="related">Related</div>
<footer>Footer</footer>
</body>
Javascript:
if(window.matchMedia("screen and (min-width: 60em) and (max-width: 90em)").matches) {
window.addEventListener("resize", function addWrapper(q) {
//Create div with id wrapper
var div = document.createElement('div');
div.id = "wrapper";
// Select aside
var selectDiv = document.querySelector("aside");
//clone
div.appendChild(selectDiv.cloneNode(true));
//Place the new wrapper at the right place in the HTML
selectDiv.parentNode.replaceChild(div, selectDiv);
//Add related to the wrapper so they're both in the wrapper
document.querySelector('#wrapper').appendChild(
document.querySelector('.related') );
});
}
I wanted to add an 'else' to remove the child (with removeChild) or delete the eventListener (with removeEventListener) when there's another screen size, but all I get is errors about that the function is not definied or other errors whatever I try.
else {
window.removeEventListener("resize", addWrapper(q));
}
Does anyone know how the wrapper can be removed when the screensize is not >60em and <90em? I'm a Javascript rookie (as might be clear ;) ). Any help is appreciated.
You could do something like this:
var addWrapper = function () {
//Don't add wrapper if already added
var wrapper = document.getElementById("wrapper");
if (wrapper !== null) return;
//Create div with id wrapper
var div = document.createElement('div');
div.id = "wrapper";
// Select aside
var selectDiv = document.querySelector("aside");
//clone
div.appendChild(selectDiv.cloneNode(true));
//Place the new wrapper at the right place in the HTML
selectDiv.parentNode.replaceChild(div, selectDiv);
//Add related to the wrapper so they're both in the wrapper
document.querySelector('#wrapper').appendChild(
document.querySelector('.related'));
};
var removeWrapper = function () {
//Don't remove if there is no wrapper
var wrapper = document.getElementById("wrapper");
if (wrapper === null) return;
//Replace wrapper with its content
wrapper.outerHTML = wrapper.innerHTML;
}
var wrapperFixer = function () {
if (window.matchMedia("screen and (min-width: 60em) and (max-width: 90em)").matches) {
addWrapper();
} else {
removeWrapper();
}
}
window.onload = function () {
window.addEventListener("resize", wrapperFixer);
//Check and add if wrapper should be added on load
wrapperFixer();
}
body {
display: flex;
height: 40em;
flex-wrap: wrap;
font-family: Helvetica, Arial, sans-serif;
color: white;
text-align: center;
}
header {
background-color: purple;
width: 30%
}
main {
background-color: pink;
width: 40%
}
aside {
background-color: deepPink;
width: 15%
}
.related {
background-color: red;
width: 15%
}
footer {
background-color: slateBlue;
width: 100%;
height: 5em;
}
#wrapper {
border: 4px solid white;
}
<body>
<header>Header</header>
<main>Main</main>
<aside>Aside</aside>
<div class="related">Related</div>
<footer>Footer</footer>
</body>
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'm currently working on an aspx Page , the main page functionality is to display a google maps path composed by several markers (huge amount) , i'd need to add a print option (A3/A4 Format) ,and i've been using the window.print() function to achieve this , as i've been stuck having issues trying with other methods (like google maps api) , here's my current issue : using window.print() i'm able to get the printing of the map with the right formats , however there's a blank space being showed on the printout , here's an example A4(1050,625):
screenshot
The code:
function print(width,height){
var cDiv = document.createElement('div');
cDiv.setAttribute('id','mainContainer');
cDiv.innerHTML='<div id="mapContainer"></div>';
var jqMapContainer = $("#map");
mapContainer = jqMapContainer[0];
var origDisplay = [],
origMapParent = mapContainer.parentNode;
body = window.document.body;
childNodes = body.childNodes;
// hide all body content
$.each(childNodes, function (i, node) {
if (node.nodeType === 1) {
origDisplay[i] = node.style.display;
node.style.display = 'none';
}
});
body.appendChild(cDiv);
var rc = document.getElementById('mapContainer');
rc.appendChild(mapContainer);
$("#mainContainer").width(width);
$("#mainContainer").height(height);
$(mapContainer).width(width);
$(mapContainer).height(height);
setTimeout(function () {
window.print();
}, 4000);
var _self = this;
// allow the browser to prepare before reverting
setTimeout(function () {
// put the chart back in
origMapParent.appendChild(mapContainer);
$("#mainContainer").remove();
// restore all body content
$.each(childNodes, function (i, node) {
if (node.nodeType === 1) {
node.style.display = origDisplay[i];
}
});
google.maps.event.trigger(map, 'resize');
}, 4000);
}
the div element that contains the map:
<div class="CenterRightColMap">
<div class="contentCC">
<div id="map" class="mapFullPage"></div>
</div>
</div>
Style:
div.mapFullPage
{
width:100%;
height:98%;
}
div.contentCC {
position:relative;
padding: 5px;
margin: 5px 5px 0px 5px;
border: 1px solid #000000;
/*background: #FFFFFF;
color: #666666;
font-family: Tahoma,Verdana,Helvetica,Helvetica-Narrow,sans-serif;*/
text-align:center;
height:100%
}
div.CenterRightColMap
{
position:absolute;
float: auto;
left:430px;
right:20px;
height:85%;
min-height:85%;
FONT-SIZE: 8pt;
background-color: #CECECE;
FONT-FAMILY: Verdana;
padding: 5px
}
Found the solution here : https://bugs.chromium.org/p/chromium/issues/detail?id=426294
Managed to fix it using adding the following style to the page
<style>.gm-style div > img {position: absolute;}</style>
Appears to be a bug from gm
I have seen this code ( http://jsfiddle.net/eMNfd/21/ ), but I want to know how to make the new div can be created to the right of the blue, that is, in horizontal mode.
document.getElementById("text").onclick = function () {
var ok = true;
if (ok === true) {
var div = document.createElement('div');
div.className = 'new-rect';
//div.style.backgroundColor = "black";
document.getElementsByTagName('body')[0].appendChild(div);
}
};
.new-rect {
background: black;
width: 20%;
height: 30px;
}
<div id="text" style="width:20%;height:30px;background-color:blue;"></div>
Thanks to all.
You can use float for this (has to be set on all divs to work), you can also use inline-block:
document.getElementById("text").onclick = function () {
var ok = true;
if (ok === true) {
var div = document.createElement('div');
div.className = 'new-rect';
//div.style.backgroundColor = "black";
document.getElementsByTagName('body')[0].appendChild(div);
}
};
body {
font-size: 0; /* to get rid of the space between the divs */
white-space: nowrap; /* to prevent wrapping on multiple lines */
}
div {
display: inline-block; /* to add divs horizontally */
}
.new-rect {
background: black;
width: 20%;
height: 30px;
}
<div id="text" style="width:20%;height:30px;background-color:blue;"></div>
I am trying to, sort of, emulate the effect here. Essentially, during scrolling, change the css (drop shadow), and when the element comes back to original position (remove shadow).
I am able to detect scroll, but not able to figure out how to detect the return to the original un-scrolled state.
HTML
<div id="container">
<ul>
<li id="one">el</li><li>el</li><li>el</li><li>el</li><li>el</li><li>el</li><li>el</li><li>el</li><li>el</li><li>el</li><li>el</li><li>el</li><li>el</li>
</ul>
</div>
CSS
html, body {
margin: 0;
padding: 0;
height: 100%;
}
#container {
height: 100px;
width: 500px;
border: 1px solid #000000;
overflow: scroll;
}
JS (with jquery)
var p = $('#one');
var position0 = p.position().top;
$('#container').scroll(function () {
if (p.position().top != position0) {
console.log('p.position: ' + p.position().top);
$('#container').css('background-color', 'pink');
}
});
JSFIDDLE: http://jsfiddle.net/nrao89m3/
PS: From console.log it doesn't seem to return to its original value at all.
Just add an else block:
var p = $('#one');
var position0 = p.position().top;
$('#container').scroll(function () {
if (p.position().top != position0) {
console.log('p.position: ' + p.position().top);
$('#container').css('background-color', 'pink');
} else {
$('#container').css('background-color', 'white');
}
});
http://jsfiddle.net/vyjbwne2/
I want to scroll 2 divs when I start the page. I add to the onload the events, but it stops here:
var cross_marquee=document.getElementById(marque)
cross_marquee.style.top=0
Can someone help me?
The code is:
var delayb4scroll=2000
var marqueespeed=1
var pauseit=0
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var actualheight=''
var actualheightDiv2=''
function scrollmarquee(){
if (parseInt(cross_marquee.style.top)>(actualheight*(-1)+8))
cross_marquee.style.top=parseInt(cross_marquee.sty le.top)-copyspeed+"px"
else
cross_marquee.style.top=parseInt(marqueeheight)+8+ "px"
}
function initializemarquee(marque, container){
var cross_marquee=document.getElementById(marque)
cross_marquee.style.top=0
marqueeheight=document.getElementById(container).o ffsetHeight
actualheight=cross_marquee.offsetHeight
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
cross_marquee.style.height=marqueeheight+"px"
cross_marquee.style.overflow="scroll"
return
}
setTimeout('lefttime=setInterval("scrollmarquee()" ,30)', delayb4scroll)
}
window.onload=initializemarquee('wtvmarquee', 'wtmarqueecontainer')
window.onload=initializemarquee("wtvmarqueeDiv2", "wtmarqueecontainerDiv2")
You're overwriting the onload event.
Create a function that initializes both marquees:
window.onload = function(e)
{
initializemarquee('wtvmarquee', 'wtmarqueecontainer');
initializemarquee("wtvmarqueeDiv2", "wtmarqueecontainerDiv2");
}
Additionally, shouldn't be cross_marquee.style.top="0px" ?
Just found another code and modified it to my situation, and its working :)
Tks for the help joel ;)
<style type="text/css">
.scrollBox {
/* The box displaying the scrolling content */
position: absolute;
top: 30px;
left: 200px;
width: 180px;
height: 200px;
border: 1px dashed #aaaaaa;
overflow: hidden;
}
.scrollTxt {
/* the box that actually contains our content */
font: normal 12px sans-serif;
position: relative;
top: 200px;
}
.scrollBox2 {
/* The box displaying the scrolling content */
position: absolute;
top: 300px;
left: 200px;
width: 180px;
height: 200px;
border: 1px dashed #aaaaaa;
overflow: hidden;
}
.scrollTxt2 {
/* the box that actually contains our content */
font: normal 12px sans-serif;
position: relative;
top: 470px;
}
</style>
<script type="text/javascript">
var scrollSpeed =1; // number of pixels to change every frame
var scrollDepth =200; // height of your display box
var scrollHeight=0; // this will hold the height of your content
var scrollDelay=38; // delay between movements.
var scrollPos=scrollDepth; // current scroll position
var scrollMov=scrollSpeed; // for stop&start of scroll
var scrollPos2=scrollDepth; // current scroll position
var scrollMov2=scrollSpeed; // for stop&start of scroll
function doScroll() {
if(scrollHeight==0) { getHeight(); }
scrollPos-=scrollMov;
if(scrollPos< (0-scrollHeight)) { scrollPos=scrollDepth; }
document.getElementById('scrollTxt').style.top=scrollPos+'px';
setTimeout('doScroll();', scrollDelay);
}
function getHeight() {
scrollHeight=document.getElementById('scrollTxt').offsetHeight;
}
function doScroll2() {
if(scrollHeight==0) { getHeight2(); }
scrollPos2 -= scrollMov2;
if(scrollPos2< (0-scrollHeight)) { scrollPos2=scrollDepth; }
document.getElementById('scrollTxt2').style.top=scrollPos2 +'px';
setTimeout('doScroll2();', scrollDelay);
}
function getHeight2() {
scrollHeight=document.getElementById('scrollTxt2').offsetHeight;
}
window.onload = function(e)
{
doScroll();
doScroll2();
}
</script>