javascript pass screen width to function - javascript

I have implemented an infinite scroll and I need to modify the width of all elements to adjust to the display width.
the code is
var elements = document.getElementsByClassName('myDiv');
for (var i = 0; i < elements.length; i++) {
elements[i].style.width = (screen.width / 2);
}
and does not work (does not change the width of the div)
but
var elements = document.getElementsByClassName('myDiv');
for (var i = 0; i < elements.length; i++) {
elements[i].style.width = "10px";
}
works
and alert(screen.width) returns correctly the screen's width.
can someone help me ?

Add the px - the unit is expected
document.querySelectorAll('.myDiv')
.forEach(div => div.style.width = `${(screen.width / 2)}px`)
.myDiv { background-color: yellow; }
<div class="myDiv" style="width:100px">Hello</div>
<div class="myDiv" style="width:200px">Hello</div>
<div class="myDiv" style="width:300px">Hello</div>
<div class="myDiv" style="width:400px">Hello</div>
<div class="myDiv" style="width:500px">Hello</div>
<div class="myDiv" style="width:600px">Hello</div>

Related

Trigger resize only once

I am trying to reverse two divs when the client's window is resized, but my function loops.
I know that this can be made very easy using flexbox, but I am more interested in understanding how to make it work using JS. Just got into learning JS and I am experimenting with functions.
when the client's window is below 58em, I want the divs to rearrange - like flex-direction: column-reverse; for example. when the window is not resized or it's size is bigger than 58em, the function should not do anything
var reverse = document.querySelectorAll(".reverse");
function reverseChildren(parent) {
for (var i = 1; i < parent.childNodes.length; i++){
parent.insertBefore(parent.childNodes[i], parent.firstChild);
}
}
window.addEventListener('resize', function () {
if (window.matchMedia("(max-width: 58em)").matches) {
for (i = 0; i < reverse.length; i++) {
reverseChildren(reverse[i]);
}
}
});
<div class=" reverse">
<div class="first">
<h4>some text</h4>
</div>
<div class="second">
<img src='https://images.unsplash.com/photo-1430026996702-608b84ce9281?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=600&h=338&fit=crop&s=363a88755a7b87635641969a8d66f7aa' alt="Registration screen">
</div>
</div>
You should listen for the match media instead of the resize event.
var reverse = document.querySelectorAll(".reverse");
/* Any other code that reverses the ordre of elements is viable within this function */
function reverseChildren(parent) {
let children = [];
for (var i = 0; i < parent.children.length; i++) {
children.push(parent.children[i]);
}
children = children.reverse().map(item => item.outerHTML).join('');
parent.innerHTML = children;
}
let media = window.matchMedia("(max-width: 58em)");
media.addListener(() => {
for (var i = 0; i < reverse.length; i++) {
reverseChildren(reverse[i]);
}
});
<div class=" reverse">
<div class="first">
<h4>some text</h4>
</div>
<div class="second">
<img src='https://images.unsplash.com/photo-1430026996702-608b84ce9281?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=600&h=338&fit=crop&s=363a88755a7b87635641969a8d66f7aa' alt="Registration screen">
</div>
</div>
<span class="mq-value"></span>

How to set an attribute as percentage in jQuery?

I am unable to set css attribute {left: $numberEquivalentToPercent} in jQuery
var targets = $('.parallax__layer__cell');
var i = 1;
for(i = 1; i <= targets.length; i++)
{
if (targets.parents('.parallax__layer--bg').length) {
//apply to only those element that have a parent having class "parallax__layer--bg"
targets.eq(i).css('left', toString(60*i)+ "%");
}
}
The above code(in JS) is expected to produce the same effect as below(in CSS)
.parallax__layer__cell:nth-child(1) { left: 0%; }
.parallax__layer__cell:nth-child(2) { left: 60%; }
.parallax__layer__cell:nth-child(3) { left: 120%; }
.parallax__layer__cell:nth-child(4) { left: 180%; }
.parallax__layer__cell:nth-child(5) { left: 240%; }
Basically I am trying to convert a static code to dynamic code
What if you put 60 * i into a variable called numPercent and then do numPercent.toString() to convert it to a string?
var targets = $('.parallax__layer__cell');
var i = 1;
for(i = 1; i <= targets.length; i++)
{
if (targets.parents('.parallax__layer--bg').length) {
//apply to only those element that have a parent having class "parallax__layer--bg"
var numPercent = 60*i;
targets.eq(i).css('left', numPercent.toString() + "%");
}
}
Here is working code:
var targets = $('.parallax__layer__cell');
var i ;
for(i = 0; i < targets.length; i++)
{
if (targets.eq(i).parents('div.parallax__layer--bg').length) {
targets.eq(i).css('left', 60*i + "%");
}
}
.parallax__layer__cell{
position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="parallax__layer--bg">
<div class="parallax__layer__cell">a</div>
</div>
<div class="parallax__layer--bg">
<div class="parallax__layer__cell">b</div>
</div>
<div class="parallax__layer--bg">
<div class="parallax__layer__cell">c</div>
</div>
<div class="parallax__layer--bg">
<div class="parallax__layer__cell">d</div>
</div>
<div class="parallax__layer--bg">
<div class="parallax__layer__cell">e</div>
</div>
<div>
<div class="parallax__layer__cell">--no parent--</div>
</div>
</div>
I believe this is a timing issue between parallax script and your script. Since css loads first parallax script works fine. But if you remove css and run your script after parallax script it may not do the same effect. Make sure your script runs before actual parallax script.

css not affecting div

I made this function to make 16 columns and rows.but I want the div that they are in to be on the right side, so for some reasons, I can't seem to change the div through (inline) css. I'm guessing its a problem with the function? Thanks for the help.
<html>
<body>
<div id="buttonContainer">
<button></button>
</div>
<div id="gridContainer" style = "left: 500px;">
</div>
</body>
<script>
const buttons = document.querySelector("#buttonContainer");
const btn1 = document.createElement("button");
btn1.classList.add("btn1");
buttonContainer.appendChild(btn1);
function divs(){
const gridContainer = document.querySelector("#gridContainer");
for(var i = 0; i < 17; i++){
var row = document.createElement("div");
row.className = "row";
for(var x = 1; x <= 17; x++){
var cell = document.createElement("div");
cell.className = "gridsquare";
cell.innerText = (i);
row.appendChild(cell);
}
gridContainer.appendChild(row);
}
}
divs();
</script>
</html>
There are different ways to move a div to the right. One is to give it a position:absolute (so it can move around freely) and then apply right : 0.
I have also removed the glitchy <button part.
const buttons = document.querySelector("#buttonContainer");
const btn1 = document.createElement("button");
btn1.classList.add("btn1");
buttonContainer.appendChild(btn1);
function divs() {
const gridContainer = document.querySelector("#gridContainer");
for (var i = 0; i < 17; i++) {
var row = document.createElement("div");
row.className = "row";
for (var x = 1; x <= 17; x++) {
var cell = document.createElement("div");
cell.className = "gridsquare";
cell.innerText = (i);
row.appendChild(cell);
}
gridContainer.appendChild(row);
}
}
divs();
#gridContainer{
position : absolute;
right: 0;
}
<div id="buttonContainer"></div>
<div id="gridContainer"></div>
EDIT : more modern/robust solution with Flexbox
The problem with position:absolute is that it kind of "detaches" the element from the rest of the DOM, so other elements start placing themselves underneath it, and it can quickly cause layout nightmares.
Here's an alternative with Flexbox :
.parent{
border : blue solid 2px;
height: 200px;
width: 100%;
display: flex;
justify-content: flex-end;
}
.child {
flex-basis : 150px; /* This is like width:150px */
background : green;
}
<div class="parent">
<div class="child"></div>
</div>

Change CSS of inner div when scroll reaches that div

I am attempting to implement a scroll function where the CSS of the inner div's change when it reaches a certain height from the top.
var $container = $(".inner-div");
var containerTop = $container.offset().top;
var documentTop = $(document).scrollTop();
var wHeight = $(window).height();
var minMaskHeight = 0;
var descriptionMax = 200;
var logoMin = -200;
var maskDelta = descriptionMax - minMaskHeight;
var $jobOverview = $container.find(".right");
var $jobLogo = $container.find(".left");
var curPlacementPer = ((containerTop - documentTop) / wHeight) * 100;
var topMax = 85;
var center = 20;
var bottomMax = -15;
//console.log("Placement: " + curPlacementPer);
function applyChanges(perOpen) {
var maskHeightChange = maskDelta * (perOpen / 100);
var opacityPer = perOpen / 100;
var newDescriptionLeft = descriptionMax - maskHeightChange;
var newLogoLeft = logoMin + maskHeightChange;
if (newDescriptionLeft <= 0) newDescriptionLeft = 0;
if (newLogoLeft >= 0) newLogoLeft = 0;
if (opacityPer >= 1) opacityPer = 1;
$jobOverview.css({
transform: "translate(" + newDescriptionLeft + "%,-50%)",
opacity: opacityPer
});
$jobLogo.css({
transform: "translate(" + newLogoLeft + "%,-50%)",
opacity: opacityPer
});
}
if (window.innerWidth > 640) {
$container.removeClass("mobile");
// console.log("Placement: " + curPlacementPer);
if (curPlacementPer <= topMax /*&& curPlacementPer >= center*/ ) {
var perOpen = ((topMax - curPlacementPer) / 25) * 100;
applyChanges(perOpen);
} else if (curPlacementPer < center /*&& curPlacementPer >= bottomMax*/ ) {
var perOpen = (((bottomMax - curPlacementPer) * -1) / 25) * 100;
applyChanges(perOpen);
} else {
$jobOverview.css({
transform: "translate(200%,-50%)",
opacity: "0"
});
$jobLogo.css({
transform: "translate(-300%,-50%)",
opacity: "0"
});
}
<div class="outer-div">
<div class="inner-div first">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div second">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div third">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div fourth">
<div class="left"></div>
<div class="right"></div>
</div>
</div>
Currently, all of the inner div's gets changed at the same time.
I noticed that when I change the $container class to equal '.first' and specify it more, it works.
Is there any way to make the inner div's change separately, relative to its height from the top? Any way I can iterate the scroll function so I can add more inner div's in the future and not have to worry about changing my scroll function?
In raw JavaScript, this is my answer:
// Define the element -- The '#fooBar' can be changed to anything else.
var element = document.querySelector("#fooBar");
// Define how much of the element is shown before something happens.
var scrollClipHeight = 0 /* Whatever number value you want... */;
// Function to change an element's CSS when it is scrolled in.
const doSomething = function doSomething() {
/** When the window vertical scroll position plus the
* window's inner height has reached the
* top position of your element.
*/
if (
(window.innerHeight + window.scrollY) - (scrollClipHeight || 0) >=
element.getBoundingClientRect().top
)
// Generally, something is meant to happen here.
element.style = "/* Yay, some CSS! */"
};
// Call the function without an event occurring.
doSomething();
// Call the function when the 'window' scrolls.
addEventListener("scroll", doSomething, false)
This is the method I use. If there are other methods, I'd love to see them as well but this is my answer for now.
consider using 3rd party jQuery plugin for easier job, like one of these:
https://github.com/xobotyi/jquery.viewport
or
https://github.com/zeusdeux/isInViewport
then you can have additional element selector e.g.: ":in-viewport"
so you can:
$(window).on('scroll',function() {
$('div').not(':in-viewport').html('');
$('div:in-viewport').html('hello');
});
Check if current scroll offset from top is bigger than the element offset from the top:
$(window).scroll(function() {
var height = $(window).scrollTop();
var element = $('#changethis'); //change this to your element you want to add the css to
if(height > element.offset().top) {
element.addClass('black'); //add css class black (change according to own css)
}
});
Html:
<div id="changethis">Test</div>
Css:
body
{
height:2000px;
}
.black
{
background-color:black;
color:white;
padding:20px;
}
Demo:
https://codepen.io/anon/pen/WZdEap
You could easily implement this in your existing code.
Below is the sample snippet code, Hope it'll work for you:
$(document).ready(function(){
topMax = 100;
topMin = 25;
$(document).scroll(function(){
$('.inner-div').each(function(){
if($(this).offset().top-$(window).scrollTop()<=topMax && $(this).offset().top-$(window).scrollTop()>=topMin){
$(this).css({'background':'#c7c7c7'});
}else{
$(this).css({'background':'inherit'});
}
});
});
});
div{
width:100%;
border:1px solid red;
padding:5px;
}
div.inner-div{
border: 1px dashed green;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer-div">
<div class="inner-div first">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div second">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div third">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div fourth">
<div class="left"></div>
<div class="right"></div>
</div>
</div>
Happy to help you! :)

How to create pair game using node values and set a setTimeout() method

I want to create a pair game that if the same textnode is matched it will set the background in white to reveal the matched textnode if not it will set a timeout and get back in original state.
The Problem of this is if I use the childNodes.nodeValue in match it saids that ChildNodes.nodeValue is not a function. And I try another code. I declare a variable that calls the element tag name of div which is I append a textNode in div. I want to compare two consecutive childNodes of div and if it is the same node, I change the color of the background to white. and I use the setTimout method, if not the color of background will go back again in original state which is black, I am pretty confused about this.
can you scan my code and help me to figure out what is the problem of this code?
here is the code.
<html>
<head>
<style>
div.row {
clear : left;
margin: auto;
width: 520px;
}
div.col {width:100px;
height:100px;
border: 3px solid black;
float : left;
margin: 10px;
font-size: 75px;
text-align: center;
background-color: black;
}
</style>
</head>
<body>
<div class="row">
<div id="00" class="col"></div>
<div id="01"class="col"></div>
<div id="02"class="col"></div>
<div id="03"class="col"></div>
</div>
<div class="row">
<div id="10" class="col"></div>
<div id="11"class="col"></div>
<div id="12"class="col"></div>
<div id="13"class="col"></div>
</div>
<div class="row">
<div id="20" class="col"></div>
<div id="21"class="col"></div>
<div id="22"class="col"></div>
<div id="23"class="col"></div>
</div>
<div class="row">
<div id="30" class="col"></div>
<div id="31"class="col"></div>
<div id="32"class="col"></div>
<div id="33"class="col"></div>
</div>
<script>
var size = 4;
var player = 0;
var board = new Array(size);
for (var i = 0; i < size; i++) {
board[i] = new Array(size);
for (var j = 0; j < size; j++) {
board[i][j] = 0;
}
}
var div_elements = document.getElementsByClassName("col");
for (var i = 0; i < div_elements.length;i++) {
div_elements[i].addEventListener("click", function() {mclick(this);});
}
var count=0;
function mclick(obj) {
if(match(div_elements.childNodes[0].nodeValue) == match(div_elements.childNodes[1].nodeValue)
{
obj.style.backgroundColor="white";
}
else{
setTimeout(function(){ obj.style.backgroundColor="white" }, 1000);
}
}
function shuffle() {
var value;
var text;
var text_node;
for (var i = 0; i < (size * size) ; i++) {
value = Math.ceil(Math.random() * 8);
board[Math.floor(i/4)][i %4] = value;
}
for (var i = 0; i < div_elements.length; i++)
{
text = board[Math.floor(i/4)][i%4];
text_node = document.createTextNode( text);
div_elements[i].appendChild(text_node);
}
}
shuffle();
</script>
</body>
</html>
You must be more specific. What kind of problem are you having? What are the error messages? What do you do that triggers the problem?
At least, put the code in a pastebin.com or something similar so that others don't need to setup a project for testing your whole stuff.

Categories