Since I figured out that new className(param) does not refer directly to an instance(param){} when it passed a constructor function, I've been trying to pass a HTML class into the instance method without changing. but it keeps detecting pseudo class of the param.
This is my code:
class Slider {
'use strict';
istouchStart(e) {
console.log(e.target);
this.coordX = e.touches[0].clientX;
return this.coordX;
}
constructor(target) {
// Variables
var _ = this;
console.log(target);
$(target).stop(true, true).on({
touchstart:_.istouchStart,
touchmove:_.istouchMove,
touchend:_.istouchEnd
});
}
}
const image = new Slider('.inline-grid');
div {
position: relative;
}
.inline-grid {
margin: 0 auto;
width: 2560px;
border: 1px solid black;
display: flex;
flex-flow: row;
overflow: hidden;
}
.wrap {
width: 100%;
display: flex;
flex-flow: row;
}
.cell {
display: flex;
flex-flow: column;
flex-shrink: 0;
width: 100%;
height: 200px;
}
.orange {
background-color: orange;
}
<div class="inline-grid">
<div class="wrap">
<div class="cell orange"></div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
how would I get the .inline-grid from the istouchStart method?
this is a second try using return and arrow function, but this one just doesn't work without showing an error.:
static istouchStart() {
return (e) => {
console.log(e.target);
this.coordX = e.touches[0].clientX;
}
}
Related
I tried to make code showing the number of component which is currently fully visible.
I used Intersection Observer API and to make it, used callback entry.intersectionRatio === 1.0.
I want to remark currently fully visible component at state currentView but it doesn't show anything.
I think currentView is not changed, althought I use useEffect
May I know which part is wrong and how to fix it??
code :
import styled from "styled-components";
import { useState, useEffect } from "react";
export default function App() {
const [currentView, setCurrentView] = useState();
useEffect(() => {
const components = document.querySelectorAll(".comp");
const componentObserver = new IntersectionObserver(function (
entries,
observer
) {
entries.forEach(function (entry) {
if (entry.isIntersecting && entry.intersectionRatio === 1.0) {
setCurrentView(entry.target.id);
}
});
});
components.forEach((comp) => {
componentObserver.observe(comp);
});
}, [currentView, setCurrentView]);
return (
<Wrap>
<div className="fixed">currentcomponent : {currentView}</div>
<div id="part-1" className="compo1 comp">
components 1
</div>
<div id="part-2" className="compo2 comp">
components 2
</div>
<div id="part-3" className="compo3 comp">
components 3
</div>
</Wrap>
);
}
const Wrap = styled.div`
border: 3px solid black;
width: 100vw;
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
.fixed {
position: sticky;
top: 0;
}
.compo1 {
border: 3px solid red;
display: flex;
justify-content: center;
align-items: center;
width: 90vw;
height: 90vh;
}
.compo2 {
border: 3px solid blue;
display: flex;
justify-content: center;
align-items: center;
width: 90vw;
height: 90vh;
}
.compo3 {
border: 3px solid green;
display: flex;
justify-content: center;
align-items: center;
width: 90vw;
height: 90vh;
}
`;
CodeSandBox :
CodeSandBox
I am working on a WordPress site and I have a snippet of html that iterates with repeating classes.
I am attempting to create a click function but only affect the element that is clicked. All in JavaScript.
As of right now my function is affecting all elements with the class name. Test code can be found at my CodePen or below.
I can accomplish this without nested loops as seen here. So my assumption is the problem lies within the second forEach loop. I would appreciate any light on the matter.
Thank you in advance.
/**
*Constructors
**/
const carousel = document.getElementsByClassName("carousel");
const btns = document.getElementsByClassName("btns");
/**
*Execute
**/
Array.from(btns).forEach((i) => {
i.addEventListener("click", (e) => {
Array.from(carousel).forEach((n) => {
if (i.classList.contains("slide-left")) {
n.scrollLeft -= 20;
} else if (i.classList.contains("slide-right")) {
n.scrollLeft += 20;
} else {
alert("ut oh");
}
});
});
});
/*
**Utilities
*/
/*containers*/
.feed-container {
position: absolute;
height: 200px;
width: 100%;
display: grid;
grid-template-columns: 1;
grid-template-rows: 1;
}
.carousel {
grid-row: 1;
grid-column: 1/5;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: 1;
grid-gap: 15px;
align-self: center;
border: 1px solid #ccc;
overflow-x: scroll;
overflow-y: hidden;
}
/*div-buttons*/
div[class*="slide-"] {
/*opacity: 0;*/
position: sticky;
grid-row: 1;
z-index: 5;
place-self: center;
transition: 0.5s;
padding: 15px;
}
.slide-left {
grid-column: 1;
}
.slide-right {
grid-column: 4;
}
/*items*/
div[class*="item-"] {
grid-row: 1;
width: 400px;
height: 200px;
}
.item-1 {
background: blue;
}
.item-2 {
background: red;
}
.item-3 {
background: grey;
}
.item-4 {
background: yellow;
}
/*scrollbar*/
::-webkit-scrollbar {
display: none;
}
/*chevrons*/
[class*="chevron-"] {
box-sizing: border-box;
position: relative;
display: block;
transform: scale(var(--ggs, 1));
width: 22px;
height: 22px;
border: 2px solid transparent;
border-radius: 25px;
}
[class*="chevron-"]::after {
content: "";
display: block;
box-sizing: border-box;
position: absolute;
width: 40px;
height: 40px;
border-bottom: 8px solid;
border-left: 8px solid;
bottom: 0;
}
.chevron-left::after {
transform: rotate(45deg);
left: 15px;
}
.chevron-right::after {
transform: rotate(-135deg);
right: 15px;
}
/*
**Exceptions
*/
.btns:hover {
cursor: pointer;
}
.opaque {
opacity: 1 !important;
}
.show {
display: block;
}
<div id="wrapper" style="display:grid; grid-template-rows:repeat(2, auto); grid-gap: 100px;">
<div>
<h1>Header</h1>
<div class="feed-container">
<div class="carousel">
<div class="item-1"></div>
<div class="item-2"></div>
<div class="item-3"></div>
<div class="item-4"></div>
</div>
<div class="slide-left btns">
<div class="chevron-left"></div>
</div>
<div class="slide-right btns">
<div class="chevron-right"></div>
</div>
</div>
</div>
<br>
<div>
<h1>Header</h1>
<div class="feed-container">
<div class="carousel">
<div class="item-1"></div>
<div class="item-2"></div>
<div class="item-3"></div>
<div class="item-4"></div>
</div>
<div class="slide-left btns">
<div class="chevron-left"></div>
</div>
<div class="slide-right btns">
<div class="chevron-right"></div>
</div>
</div>
</div>
</div>
It's because you're getting all the elements with class name carousel and then looping through them with each click.
const carousel = document.getElementsByClassName("carousel");
Instead what you need to do is get the carousels only under the button's parent when you trigger the click event
eg something like this:
Array.from(btns).forEach((i) => {
i.addEventListener("click", (e) => {
const targetElement = e?.target || e?.srcElement;
const parent = targetElement.parentElement();
const carousel = Array.from(parent.getElementsByClassName("carousel"));
carousel.forEach((n) => {
if (i.classList.contains("slide-left")) {
n.scrollLeft -= 20;
} else if (i.classList.contains("slide-right")) {
n.scrollLeft += 20;
} else {
alert("ut oh");
}
});
});
});
I took a look at the following as recommend and it seems to do the trick.
I created a variable that calls the parentNode "forEach()" button clicked. Oppose to looping through each element.
Working example, codePen
const carousel = document.querySelectorAll(".carousel");
const btns = document.querySelectorAll(".btns");
btns.forEach((i) => {
i.addEventListener("click", () => {
var x = i.parentNode;
var y = Array.from(x.querySelectorAll(".carousel"));
y.forEach((n) => {
if (i.classList.contains("slide-left")) {
n.scrollLeft -= 20;
} else {
n.scrollLeft += 20;
}
});
});
});
I am building a website with a set of squares in a grid shape. I would like them to be perfect squares, with equal width and height. It works very well, except they flash between fitting two and three on a line when you resize the page. Here is the code:
const get = (querySelector) => document.querySelector(querySelector),
getAll = (querySelector) => document.querySelectorAll(querySelector),
getClass = (className) => document.getElementsByClassName(className),
getTag = (tagName) => document.getElementsByTagName(tagName);
function resizePosts() {
if (get('.post')) {
for (let i = 0; i < getClass('post').length; i++) {
getClass('post')[i].style.width = getClass('post')[i].parentElement.offsetWidth/3-10.982;
getClass('post')[i].style.height = getClass('post')[0].offsetWidth;
}
}
window.addEventListener('resize', resizePosts, false);
}
window.addEventListener('load', resizePosts, false);
window.addEventListener('resize', resizePosts, false);
.posts {
font-size: 2.5em;
font-family: 'Lato', sans-serif;
padding: 0 25px;
flex-wrap: wrap;
display: flex;
min-height: 150px;
}
.posts-themselves {
width: 100%;
display: flex;
flex-wrap: wrap;
}
.post {
border: 0.5px solid black;
margin: 5px;
width: 33%;
overflow: hidden;
}
<div class = 'posts'>
<div class = 'posts-themselves'>
<div class = 'post'>
</div>
<div class = 'post'>
</div>
<div class = 'post'>
</div>
<div class = 'post'>
</div>
</div>
</div>
Please help me set it to the correct size!
You need to add the unit of measure of the dimensions ("px")
const get = (querySelector) => document.querySelector(querySelector),
getAll = (querySelector) => document.querySelectorAll(querySelector),
getClass = (className) => document.getElementsByClassName(className),
getTag = (tagName) => document.getElementsByTagName(tagName);
function resizePosts() {
if (get('.post')) {
for (let i = 0; i < getClass('post').length; i++) {
getClass('post')[i].style.width = getClass('post')[i].parentElement.offsetWidth/3-10.982 +"px";
getClass('post')[i].style.height = getClass('post')[0].style.width;
}
}
}
window.addEventListener('load', resizePosts, false);
window.addEventListener('resize', resizePosts, false);
.posts {
font-size: 2.5em;
font-family: 'Lato', sans-serif;
padding: 0 25px;
flex-wrap: wrap;
display: flex;
min-height: 150px;
}
.posts-themselves {
width: 100%;
display: flex;
flex-wrap: wrap;
}
.post {
border: 0.5px solid black;
margin: 5px;
overflow: hidden;
}
<div class = 'posts'>
<div class = 'posts-themselves'>
<div class = 'post'>
</div>
<div class = 'post'>
</div>
<div class = 'post'>
</div>
<div class = 'post'>
</div>
</div>
</div>
This question already has answers here:
Flex elements ignore percent padding in Firefox
(4 answers)
Closed 4 years ago.
In my example code, please click on the Generate Content button in order to understand the issue.
Once you click on the button, you can see all of the flex items(.each-result) generate. They are almost completely wrapped by the div/flexbox (.result-container), indicated by the blue dotted border. If I remove the margins from flex-items, it fits perfectly into the div. However, when I add the margins, the parent div (ie. the flexbox) doesn't expand to it's full width; it remains the same width as when there was no margin.
Is there anyway to change this so that the div expands when adding margin?
const leftArrow = document.querySelector('#left-arrow');
const rightArrow = document.querySelector('#right-arrow');
const rootDiv = document.querySelector('#root');
const generateButton = document.querySelector("#button-generate");
var navMargin = '';
let rootContainerWidth = window.getComputedStyle(rootDiv, null).getPropertyValue("width");
console.log(`Window size onload: ${rootContainerWidth}`);
window.addEventListener('resize', () => {
rootContainerWidth = window.getComputedStyle(rootDiv, null).getPropertyValue("width");
console.log(`The new window size is ${rootContainerWidth}`);
})
//This code basically generates the content within the div
generateButton.addEventListener("click", () => {
for (let i = 0; i < 10; i++) {
const newDiv = document.createElement("div");
newDiv.classList.add("each-result");
newDiv.appendChild(addImg("https://uk.usembassy.gov/wp-content/uploads/sites/16/please_read_icon_150x150.jpg"));
rootDiv.appendChild(newDiv);
}
rootDiv.firstElementChild.classList.add('nav-margin');
navMargin = document.querySelector('.nav-margin');
});
//These enable the arrow to scroll through the dynamically generated content
// function navArrow () {
// leftArrow.addEventListener('click', () => {
// });
// rightArrow.addEventListener('click', () => {
// if ()
// });
// }
//Simple function to create and image element with the src attribute set in one line
function addImg(url) {
const newImg = document.createElement("img");
newImg.setAttribute("src", url);
return newImg;
}
html, body {
height: 100%;
}
button {
position: relative;
z-index: 1
width: auto;
height: 50px;
}
.container {
display: flex;
justify-content: center;
position: relative;
top: 15%;
z-index: 0
}
.each-result {
height: 150px;
width: 150px;
border: 3px dotted red;
margin: 0 1%;
}
img {
height: 100%;
width: auto;
}
.nav-arrows {
display: flex;
justify-content: space-between;
width: 100%;
height: auto;
position: absolute;
background: clear;
pointer-events: none;
}
#left-arrow, #right-arrow {
pointer-events: auto;
}
#root-container {
display: flex;
align-items: center;
border: 1px solid black;
height: 200px;
position: relative;
flex-flow: row no-wrap;
/* overflow: hidden; */
width: 100%;
}
.result-container {
display: flex;
border: 2px blue dotted;
}
<script src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<div class="container">
<div class="nav-arrows">
<button id="left-arrow"><i class="fas fa-arrow-alt-circle-left"></i>
</button>
<button id="right-arrow"> <i class="fas fa-arrow-alt-circle-right"></i>
</button>
</div>
<div id="root-container">
<div id="root" class="result-container">
</div>
</div>
</div>
<button id="button-generate">Generate Content</button>
If the margin can be a fixed value (instead of a percent), we can calc() the width of the element to account for the margin. For example, if we wanted a margin of 20px we'd do the following on the .each-result elements:
.each-result {
width: calc(10% + 20px);
margin: 0 20px;
}
Here's the working demo:
const leftArrow = document.querySelector('#left-arrow');
const rightArrow = document.querySelector('#right-arrow');
const rootDiv = document.querySelector('#root');
const generateButton = document.querySelector("#button-generate");
var navMargin = '';
let rootContainerWidth = window.getComputedStyle(rootDiv, null).getPropertyValue("width");
console.log(`Window size onload: ${rootContainerWidth}`);
window.addEventListener('resize', () => {
rootContainerWidth = window.getComputedStyle(rootDiv, null).getPropertyValue("width");
console.log(`The new window size is ${rootContainerWidth}`);
})
//This code basically generates the content within the div
generateButton.addEventListener("click", () => {
for (let i = 0; i < 10; i++) {
const newDiv = document.createElement("div");
newDiv.classList.add("each-result");
newDiv.appendChild(addImg("https://uk.usembassy.gov/wp-content/uploads/sites/16/please_read_icon_150x150.jpg"));
rootDiv.appendChild(newDiv);
}
rootDiv.firstElementChild.classList.add('nav-margin');
navMargin = document.querySelector('.nav-margin');
});
//These enable the arrow to scroll through the dynamically generated content
// function navArrow () {
// leftArrow.addEventListener('click', () => {
// });
// rightArrow.addEventListener('click', () => {
// if ()
// });
// }
//Simple function to create and image element with the src attribute set in one line
function addImg(url) {
const newImg = document.createElement("img");
newImg.setAttribute("src", url);
return newImg;
}
html, body {
height: 100%;
}
button {
position: relative;
z-index: 1
width: auto;
height: 50px;
}
.container {
display: flex;
justify-content: center;
position: relative;
top: 15%;
z-index: 0
}
.each-result {
height: 150px;
width: calc(10% + 20px);
margin: 0 20px;
border: 3px dotted red;
}
img {
height: 100%;
width: auto;
}
.nav-arrows {
display: flex;
justify-content: space-between;
width: 100%;
height: auto;
position: absolute;
background: clear;
pointer-events: none;
}
#left-arrow, #right-arrow {
pointer-events: auto;
}
#root-container {
display: flex;
align-items: center;
border: 1px solid black;
height: 200px;
position: relative;
flex-flow: row no-wrap;
/* overflow: hidden; */
width: 100%;
}
.result-container {
display: flex;
border: 2px blue dotted;
}
<script src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<div class="container">
<div class="nav-arrows">
<button id="left-arrow"><i class="fas fa-arrow-alt-circle-left"></i>
</button>
<button id="right-arrow"> <i class="fas fa-arrow-alt-circle-right"></i>
</button>
</div>
<div id="root-container">
<div id="root" class="result-container">
</div>
</div>
</div>
<button id="button-generate">Generate Content</button>
I am trying to keep a seo friendly and semantic structure for my DOM, without repeating whole elements to display them in various positions.
My layout is based on display: flex items. I try to achieve the following:
Important things to know:
I do not want to show/hide divs based on the window width (to avoid unnecessary duplicates)
None of the divs has a known or fixed height
On desktops the divs should be vertical centered, while the right column builds a tag-team (behaves like one single div)
The layout needs to support at least IE11+
Is there a css only solution to achieve this?
If not, it would be easy to cut out the green div and paste its content into the pink one using javascript. But I do have concerns about the performance and "flickering" using this, although resizing the browser makes it more complicated. Do I make this needlessly complicated?
Here is fiddle showing a working solution but with javascript:
CODEPEN DEMO
In general, you can't do this with Flexbox alone, though there might be a compromise based on each given case.
With Flexbox alone, using fixed height, you can accomplish this
* {
box-sizing: border-box;
}
body, html {
margin: 0;
}
.flex {
width: 90%;
margin: 5vh auto;
height: 90vh;
background: rgba(0, 0, 0, 0.05);
display: flex;
flex-flow: column wrap;
}
.flex div {
flex: 1;
width: 50%;
}
.flex div:nth-child(2) {
order: -1;
}
.flex::before {
content: '';
height: 100%;
}
#media (max-width:768px) {
.flex div {
width: auto;
}
.flex::before {
display: none;
}
.flex div:nth-child(2) {
order: 0;
}
}
/* styling */
.flex-child {
color: white;
font-size: 2em;
font-weight: bold;
}
.flex-child:nth-child(1) {
background: #e6007e;
}
.flex-child:nth-child(2) {
background: #f4997c;
}
.flex-child:nth-child(3) {
background: #86c06b;
}
<div class="flex">
<div class="flex-child">
<div>Top/Right</div>
</div>
<div class="flex-child">
<div>Center/Left</div>
</div>
<div class="flex-child">
<div>Bottom/Right</div>
</div>
</div>
In this case, where no fixed height is allowed, you can combine Flexbox and float.
By set up it for mobile using Flexbox where you add the center item first in the markup and then, with order, move it between the top and bottom.
With a media query you then simply make the flex container a block element and use float to position the left to the left and the right to the right.
* {
box-sizing: border-box;
}
body, html {
margin: 0;
}
.flex {
max-width: 1024px;
width: 90%;
margin: 5vh auto;
height: 90vh;
background: rgba(0, 0, 0, 0.05);
display: flex;
flex-direction: column;
}
.flex-child {
color: white;
font-size: 2em;
font-weight: bold;
padding: 5%;
flex-basis: 33.333%;
display: flex;
align-items: center;
}
.flex-child:nth-child(1) {
background: #e6007e;
order: 1;
}
.flex-child:nth-child(2) {
background: #f4997c;
}
.flex-child:nth-child(3) {
background: #86c06b;
order: 2;
}
#media (min-width: 768px) {
.flex {
display: block;
}
.flex-child {
width: 50%;
}
.flex-child:nth-child(1) {
float: left;
height: 100%;
}
.flex-child:nth-child(2),
.flex-child:nth-child(3) {
float: right;
height: 50%;
}
}
<div class="flex">
<div class="flex-child">
<div>Center/Left</div>
</div>
<div class="flex-child">
<div>Top/Right</div>
</div>
<div class="flex-child">
<div>Bottom/Right</div>
</div>
</div>
Update
Here is another version combining Flexbox with position: absolute, which also vertically center the items in desktop mode
Updated, added a script to control so the absolute positioned element won't get bigger than the right items, and if so, adjust the flex containers height.
Note, the script is by no means optimized, it is only there to show how a fix in certain situations
(function() {
window.addEventListener("resize", resizeThrottler, false);
var fp = document.querySelector('.flex');
var fi = fp.querySelector('.flex-child:nth-child(1)');
var resizeTimeout;
function resizeThrottler() {
// ignore resize events as long as an actualResizeHandler execution is in the queue
if ( !resizeTimeout ) {
resizeTimeout = setTimeout(function() {
resizeTimeout = null;
actualResizeHandler();
// The actualResizeHandler will execute at a rate of 15fps
}, 66);
}
}
function actualResizeHandler() {
// handle the resize event
if (fp.offsetHeight <= fi.offsetHeight) {
fp.style.cssText = 'height: '+fi.offsetHeight+'px';
} else {
fp.style.cssText = 'height: auto';
}
}
window.addEventListener('load', function() {
actualResizeHandler();
})
}());
* {
box-sizing: border-box;
}
body, html {
margin: 0;
}
.flex {
position: relative;
max-width: 1024px;
width: 90%;
margin: 5vh auto;
height: 90vh;
background: rgba(0, 0, 0, 0.05);
display: flex;
flex-direction: column;
}
.flex-child {
color: white;
font-size: 2em;
font-weight: bold;
padding: 5%;
}
.flex-child:nth-child(1) {
order: 1;
}
.flex-child:nth-child(3) {
order: 2;
}
.flex-child:nth-child(1) div {
background: #e6007e;
}
.flex-child:nth-child(2) div {
background: #f4997c;
}
.flex-child:nth-child(3) div {
background: #86c06b;
}
#media (min-width: 768px) {
.flex {
justify-content: center;
}
.flex-child {
width: 50%;
}
.flex-child:nth-child(1) {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.flex-child:nth-child(n+2) {
margin-left: 50%;
}
}
<div class="flex">
<div class="flex-child">
<div>Center/Left<br>with more<br>content<br>than any<br>of the<br>other items<br>other items<br>other items<br>other items<br>other items</div>
</div>
<div class="flex-child">
<div>Top/Right<br>with more<br>content</div>
</div>
<div class="flex-child">
<div>Bottom/Right<br>with more</div>
</div>
</div>
With script one can also reorder/move items between elements.
Stack snippet
You can also combine this with a media query, and use it to do the actual re-order of the elements
$( document ).ready(function() {
$(window).resize(function() {
if ($( window ).width() < 600 ) {
$(".one").insertBefore("#b");
} else {
$(".one").insertBefore(".two");
}
});
});
.outer, #flex, #flex2 {
display: flex;
flex-direction: column;
}
#a {
order: 4;
background: #ccc;
}
#b {
order: 1;
background: #aaa;
}
#c {
order: 3;
background: #d33;
}
.one {
order: 2;
background: #aaa;
}
.two {
order: 5;
background: #aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
<div id="flex">
<div id="a">A</div>
<div id="b">B</div>
<div id="c">C</div>
</div>
<div id="flex2">
<div class="one">Show me 2nd</div>
<div class="two">Show me 5th</div>
</div>
</div>
Update 2 (answered at another question but later moved here)
If we talk about smaller items, like a header or smaller menus, one can do what many website platform providers like "squarespace", "weebly", "wordpress", etc does. Their templates holds different markup structures, where an item sometimes exist twice, one visible for desktop, another for mobile.
Also, being so small, there will be less to nothing when it comes to performance (and personally I don't see anymore issue with this than having duplicate CSS rules, one for each screen size, and happily do this instead of introducing script).
Fiddle demo
Stack snippet
.container {
display: flex;
}
.container > div {
width: 50%;
}
.container div:nth-child(-n+2) {
border: dashed;
padding: 10px;
}
.container > div:nth-child(1) {
display: none; /* hide outer "Flower" */
}
#media (max-width:768px) {
.container {
flex-direction: column;
}
.container div {
width: auto;
}
.container div:nth-child(1) {
display: block; /* show outer "Flower" */
}
.container div:nth-child(3) div:nth-child(1) {
display: none; /* hide inner "Flower" */
}
}
<div class="container">
<div>Flower</div>
<div>Tree</div>
<div>
<div>Flower</div>
<div>Bee</div>
</div>
</div>