Can't style with SASS/SCSS in React properly - javascript

Take this SCSS stylesheet:
#import "../vars";
img.userIcon {
&.regular {
max-width: 64px;
max-height: 64px;
}
&.small {
max-width: 32px;
max-height: 32px;
}
border-radius: 50%;
border: 2px solid $bg-light;
}
How on earth do I get my page to recognise the .regular or .small?
This my UserIcon.tsx that applies this styling:
import styles from "../styles/components/UserIcon.module.scss";
type Props = {
src: string,
variant?: "regular" | "small"
}
export default function UserIcon({ src, variant = "regular" }: Props) {
return <img className={`${styles.userIcon} ${variant} mb-2`} src={src} />
}
Now, this obviously won't work because somewhere along the lines, the class names are all jumbled up and look like this:
<img class="UserIcon_userIcon__1jFAP regular mb-2">
Which is odd, because it doesn't ever do this to the boostrap scss files that I have imported.
So I need to know either:
How to remove the class name renaming.
How to implement .regular and .small properly, such that it uses the jumbled up name.

pass variant as key argument to your styles object:
return <img className={`${styles.userIcon} ${styles[variant]} mb-2`} src={src} />

Can you try something like that.
#import "../vars";
img.userIcon {
border-radius: 50%;
border: 2px solid $bg-light;
}
img.regular {
max-width: 64px;
max-height: 64px;
}
img.small {
max-width: 32px;
max-height: 32px;
}
import styles from "../styles/components/UserIcon.module.scss";
type Props = {
src: string,
variant?: "regular" | "small"
}
export default function UserIcon({ src, variant = "regular" }: Props) {
return <img className={`${styles.userIcon} ${styles[variant]} mb-2`} src={src} />
}
Tell me if it solved your problem

Related

How to get auto-resizing textarea passed as props? Works on it's own, but not as a prop

I am working on a new component for textareas and want to give them the ability to do three things; autofocus, debounce (still working on that) and autogrow/resize based on value.
I have been given a base component on which to work with and there are a few computed properties that I have been given that I'm not too familar with. From what I understand though, I shouldnt need them to be able to make these new props work.
I have the autofocus working perfectly as a passed prop, but the autogrow/resize has been giving me some trouble. In an isolated instance, I can get it to work, but passed as a prop with this basecomponent, I cannot managed to get it working.
When I try and add :value="value" for the v-model to work, I get an error:
:value="value" conflicts with v-model on the same element because the latter already expands to a value binding internally
I imagine this is because it's clashing with the v-model="model" above, but I'm not sure what to do with it from there.
I've attached the version that does work at the bottom.
My question is, what am I doing wrong in the CcInput-App.vue relation that won't make it work like the isolated version below?
Here's a link to the github repo as well!
If you need anymore information please do not hesitate to ask!
CcInput
<template>
<div class="cc-input">
<input
v-if="propsToPass.type !== 'textarea'"
v-bind="propsToPass"
v-model="model"
ref="input"
/>
<textarea
v-if="propsToPass.type === 'textarea'"
v-bind="propsToPass"
v-model="model"
ref="textarea"
/>
</div>
</template>
<script>
export default {
name: 'CcInput',
props: {
/** v-model */
value: { type: [String, Number], default: '' },
valueType: { type: [String, undefined], default: undefined },
autofocus: { type: Boolean, default: false },
autogrow: { type: Boolean, default: false },
},
mounted() {
if (this.autofocus) {
if (this.propsToPass.type !== 'textarea') {
this.focusInput()
} else {
this.focusTextArea()
}
}
},
data() {
return {
innerValue: this.value,
}
},
methods: {
focusInput() {
this.$refs.input.focus()
},
focusTextArea() {
this.$refs.textArea.focus()
},
},
computed: {
listenersWithoutInput() {
return { ...this.$listeners, input: undefined }
},
model: {
get() {
return this.value
},
set(val) {
const { propsToPass } = this
if (propsToPass.type === 'number') {
const valAsNumberIfNotNaN = !isNaN(Number(val)) ? Number(val) : val
this.$emit('input', valAsNumberIfNotNaN)
return
}
this.$emit('input', val)
},
},
propsToPass() {
const { $attrs, valueType } = this
const type = $attrs.type ? $attrs.type : valueType === 'number' ? 'number' : undefined
return { ...$attrs, type }
},
},
}
</script>
<style lang="sass">
.cc-input
min-width: 0
max-width: 100%
display: flex
flex-wrap: nowrap
align-items: center
position: relative
textarea, input
padding: 10px
min-width: 0
width: 100%
min-height: 24px
line-height: 24px
outline: none
box-shadow: none
-webkit-appearance: none
border: none
z-index: 2
position: relative
.cc-input
min-width: 0
max-width: 100%
display: flex
flex-wrap: nowrap
align-items: center
position: relative
textarea, input
padding: 10px
min-width: 0
width: 100%
min-height: 24px
line-height: 24px
outline: none
box-shadow: none
-webkit-appearance: none
border: none
z-index: 2
position: relative
background: none
textarea
box-sizing: border-box
min-height: 100px !important
&::after, &::before
border-radius: 4px
position: absolute
top: 0
bottom: 0
left: 0
right: 0
content: ''
border-style: solid
transition: border-color 300ms ease
&::after
border-width: 1px
border-color: rgba(0, 0, 0, 0.24)
&::before
border-width: 2px
border-color: transparent
&:focus-within::after
border-color: transparent
&:focus-within::before
border-color: purple
</style>
App.vue
<template>
<div class="home">
<div class="textarea">
autofocus
<CcInput valueType="textarea" :autofocus="true" />
</div>
<div class="textarea">
debounce
<CcInput valueType="textarea" :debounce="300" />
</div>
<div class="textarea">
autogrow
<CcInput valueType="textarea" :autogrow="true" />
</div>
</div>
</div>
</template>
<script>
import CcInput from '../components/CcInput.vue'
export default {
name: 'App',
components: {
CcInput,
},
}
</script>
<style lang="sass" scoped>
*
width: 50vw
left: 50%
.textarea
text-align: center
</style>
Autogrow.vue
<template>
<div>
<textarea class="textarea" name="body" id="body" #input="autogrow($event)"></textarea>
<textarea class="textarea" name="anotherbody" id="anotherbody"></textarea>
</div>
</template>
<script>
export default {
name: 'Autogrow',
},
methods: {
autogrow(e) {
e.target.style.height = 'auto'
e.target.style.height = `${e.target.scrollHeight}px`
},
},
}
</script>
<style lang="sass" scoped>
.textarea
box-sizing: border-box
width: 100%
padding: 20px
border-radius: 8px
</style>
The bug is in the propsToPass computed property, where it defaults type to undefined when valueType is not "number":
// Ccinput.vue
export default {
computed: {
propsToPass() {
const { $attrs, valueType } = this
const type = $attrs.type ? $attrs.type : valueType === 'number' ? 'number' : undefined
return { ...$attrs, type }
},
}
}
Given a valueType of "textarea", propsToPass.type is undefined, which does not satisfy the condition required to render the textarea with the autogrow behavior:
<textarea v-if="propsToPass.type === 'textarea'" ... />
One way to fix this is to update the condition to check valueType instead of propsToPass.type:
<textarea v-if="valueType === 'textarea'" ... />
and update propsToPass.type reference to use valueType:
// if (this.propsToPass.type !== 'textarea') {
if (this.valueType !== 'textarea') {
As an aside, you have a typo in this.$refs.textArea:
// this.$refs.textArea.focus() ❌
^
this.$refs.textarea.focus() ✅

variable css not applying in react js

this is a react app. my css class is not changing even though the state assign to track the boolean value is changing. I've passed my states accordingly for this still not working. here is the github url
my app.js file -
import React, { useState } from "react";
// Import Styles
import "./styles/App.css";
// Import Components
import Hello from "./components/Hello";
import Rectangle from "./components/Rectangle";
import Button from "./components/Button";
function App() {
const [colorStatus, setColorStatus] = useState(false);
return (
<div className="App">
<Hello />
<Rectangle colorStatus={colorStatus} />
<Button colorStatus={colorStatus} setColorStatus={setColorStatus} />
</div>
);
}
export default App;
button.js -\
import React from "react";
const Button = ({ colorStatus, setColorStatus }) => {
return (
<div className="button">
<button className="btn-1" onClick={() => setColorStatus(!colorStatus)}>
Press
</button>
</div>
);
};
export default Button;
rectangle.js -
import React from "react";
const Rectangle = ({colorStatus}) => {
return <div className={`rectangle ${colorStatus ? 'active-rectangle' : '' }`}></div>;
};
export default Rectangle;
necessary css -
.rectangle {
width: 50vw;
height: 50vh;
background: rgba(255, 0, 0, 0.4);
position: fixed;
top: 30%;
left: 35%;
}
.active-rectangle {
width: 50vw;
height: 50vh;
background: rgba(0, green, 0, 0.4);
position: fixed;
top: 30%;
left: 35%;
}
Your .active-rectangle css-rule needs correction like so :-
.active-rectangle {
width: 50vw;
height: 50vh;
background: rgba(0, 255, 0, 0.4);
position: fixed;
top: 30%;
left: 35%;
}
So your state should be getting updated and the active-rectangle class is getting applied. Just the background property isn't getting applied properly. Rest must still be getting applied.
background isn't getting applied properly because you cannot use green when a decimal value is expected inside rgba(...).
Actually your css class is getting changed (according to the url you provided).
Problem seems to be with the usage of background: rgba(0, green, 0, 0.4). Specifically in rgba(0, green, 0, 0.4).
Instead of green, it should have been a number from 0 to 255 to denote the green part of the colour.
G of R-G-B-A from rgba function you are using
checkout https://cssreference.io/property/background-color/
The problem, as said here before is the background property
Lets refactor the code a bit while we are in it.
.rectangle {
width: 50vw;
height: 50vh;
background: rgba(255, 0, 0, 0.4);
position: fixed;
top: 30%;
left: 35%;
}
.rectangle.active {
background: rgba(0, 255, 0, 0.4);
}
import React from "react";
const Rectangle = ({colorStatus}) => {
return <div className={`rectangle ${colorStatus ? 'active' : '' }`}></div>;
};
export default Rectangle;
Sandbox: https://codesandbox.io/s/friendly-galileo-gwzbh?file=/src/components/Rectangle.js

React CSS class gets override automatically on production server

I am facing a weird CSS issue in my React project. A particular part of the JSX <div> has a class applied to it and added some style properties in the main .css file of the project. In local development, everything works fine but as soon as the build is created and uploaded to the production server, that particular part of the JSX <div> CSS class changes and the styling gets distorted.
Example:
Original JSX
import React, { useEffect, useState, useContext } from "react";
import Tooltip from "#material-ui/core/Tooltip";
import { withStyles, makeStyles } from "#material-ui/core/styles";
import Slider from "#material-ui/core/Slider";
const useStyles = makeStyles((theme) => ({
root: {
width: 450,
},
margin: {
height: 100,
},
}));
const PrettoSlider = withStyles({
root: {
color: "red",
height: 8,
},
thumb: {
height: 24,
width: 24,
backgroundColor: "#fff",
border: "2px solid currentColor",
marginTop: -8,
marginLeft: -12,
"&:focus,&:hover,&$active": {
boxShadow: "inherit",
border: "2px solid #fff407 !important",
},
},
active: {
backgroundColor: "#fff407",
},
})(Slider);
const CustomizedSlider = ({
id,
abbr,
type,
minElig,
maxElig,
}) => {
useEffect(() => {
setValue(sliderPreviousValue);
}, [sliderPreviousValue]);
const classes = useStyles();
return (
<>
<div className={classes.root}>
{type === "intervention" ? (
<ProgressBar max={maxElig} value={sliderValue} />
) : null}
{renderSlider}
</div>
</>
);
};
Original DOM:
<div class="diabMetr clearfix">
<span class="diabLabl">Diabetes</span>
<div class="makeStyles-root-1">
<span class="MuiSlider-root WithStyles(ForwardRef(Slider))-root-3 MuiSlider-colorPrimary"><span class="MuiSlider-rail WithStyles(ForwardRef(Slider))-rail-8"></span><span class="MuiSlider-track WithStyles(ForwardRef(Slider))-track-7" style="left: 0%; width: 83.3333%;"></span><input type="hidden" value="200"><span class="MuiSlider-thumb WithStyles(ForwardRef(Slider))-thumb-4 MuiSlider-thumbColorPrimary PrivateValueLabel-open-12 PrivateValueLabel-thumb-11" tabindex="0" role="slider" data-index="0" aria-label="pretto slider" aria-orientation="horizontal" aria-valuemax="240" aria-valuemin="0" aria-valuenow="200" style="left: 83.3333%;"><span class="PrivateValueLabel-offset-13 MuiSlider-valueLabel WithStyles(ForwardRef(Slider))-valueLabel-6"><span class="PrivateValueLabel-circle-14"><span class="PrivateValueLabel-label-15">200</span></span></span></span></span>
<div class="valueOuter clearfix"><label class="valueLeft">0</label><label class="valueRight">240</label></div>
</div>
</div>
The CSS for this JSX is:
.diabMetr {
padding-top: 10px;
span.diabLabl {
display: inline-block;
width: 200px;
text-align: left;
font-size: 12px;
line-height: 30px;
text-align: right;
#include respond-to(media-xl) {
width: 120px;
}
}
span.MuiSlider-root {
width: 100%;
padding: 0;
height: 0px;
.MuiSlider-rail {
height: 30px;
border-radius: 15px;
background: #e8e8e8;
opacity: 1;
}
.MuiSlider-track {
height: 30px;
background: #88d479;
border-radius: 15px;
}
.MuiSlider-thumb {
z-index: 12;
width: 35px;
height: 35px;
border-radius: 50%;
margin-left: -17px;
border: #88d479 solid 2px;
margin-top: -3px;
}
.MuiSlider-markLabel.MuiSlider-markLabelActive:last-child() {
right: 0 !important;
}
}
}
.makeStyles-root-1 {
width: calc(100% - 220px) !important;
float: right;
margin-top: -22px;
}
The DOM changes after build and uploaded to the server:
<div class="diabMetr clearfix">
<span class="diabLabl">Diabetes</span>
<div class="jss16">
<span class="MuiSlider-root jss18 MuiSlider-colorPrimary"><span class="MuiSlider-rail jss23"></span><span class="MuiSlider-track jss22" style="left: 0%; width: 83.3333%;"></span><input type="hidden" value="200"><span class="MuiSlider-thumb jss19 MuiSlider-thumbColorPrimary jss27 jss26" tabindex="0" role="slider" data-index="0" aria-label="pretto slider" aria-orientation="horizontal" aria-valuemax="240" aria-valuemin="0" aria-valuenow="200" style="left: 83.3333%;"><span class="jss28 MuiSlider-valueLabel jss21"><span class="jss29"><span class="jss30">200</span></span></span></span></span>
<div class="valueOuter clearfix"><label class="valueLeft">0</label><label class="valueRight">240</label></div>
</div>
</div>
The CSS for the class .jss16 is:
.jss16 {
width: 450px;
}
Issue to notice
Only the class .makeStyles-root-1 gets replaced with some random class .jss16 when the build gets uploaded to the server and the CSS changes accordingly, the rest of the JSX remains unchanged. I tried searching for the class .jss16 everywhere in the code, but it's not found. Also, everything works fine on localhost.
I tried adding the CSS properties to the .jss16 like this:
.jss16 {
width: 450px;
width: calc(100% - 220px) !important;
margin-top: -22px;
float: right;
}
and then re-initiate the uploading process but then instead of .jss16, another class is replaced something like .jss42. This keeps on repeating and does not work on any new build created.
I also tried the following CSS:
.diabMetr + span + div {
width: 450px;
width: calc(100% - 220px) !important;
margin-top: -22px;
float: right;
},
but this also didn't help. The styling of the app still remains distorted (incorrect, not as on localhost).
I spent several hours searching for this but in vain. If anyone can assist me in understanding this error and resolve the same, will be highly appreciated. Thanks in advance!
there are quite a few issues with this code. First in jsx CSS class is given as className as #Max has mentioned in his/her answer.
Another issue is that #material-ui's makeStyle doesn't work in this way. The classNames inside the makeStyle change to random names in the build stage. This happens to keep the classNames uniques, this is #material-ui's feature. I'd suggest you to read this #matrial-ui's documentation about makeStyles. And here a code example is provided.
To use makeStyles classes you've to hook it into your component.
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
const useStyles = makeStyles({
root: {
backgroundColor: 'red',
color: props => props.color,
},
});
export default function MyComponent(props) {
const classes = useStyles(props);
return (
<div className={classes.root}>
Lorem iosum poder
</div>
);
}
Update
According to your jsx code, add the styles which you've added in css class .makeStyles-root-1 in the useStyles object. It'll add the styles to the element.
After adding those CSS styles in useStyles this object will look like this:-
const useStyles = makeStyles((theme) => ({
root: {
width: 'calc(100% - 220px) !important',
float: 'right',
marginTop: '-22px'
},
margin: {
height: 100,
},
}));
The root class will contain those styles and it'll be applied without providing the styles separately from the CSS file.
Solution
I am not sure what component creates the div with "jss16" class, assume it is ExternalComponent.
You should add a custom className (assuming ExternalComponent handles this correctly):
<ExternalComponent className="myclass">
...
</ExternalComponent>
this will create a DOM like this:
<div class="jss16 myclass">
...
</div>
Sou you can create css for myclass:
.myclass {
width: calc(100% - 220px) !important;
float: right;
margin-top: -22px;
}
Explanation
ExternalComponent uses jss to dynamically generate css classes, so you cant rely on the name of the dynamically generated class. In most of the cases, components with custom classes should append props.className to the generated jss like this:
return (
<div className={jssClassname + props.className ? ' ' + props.className : ''}>
{children}
</div>
);
I couldn't reproduce the error because I had some syntax issues, so I wonder if fixing these, the build will behave correctly:
Add closing / to input
Write style's using objects, example style={{left: '0%', width: '83.3333%'}}
Update class to className
Update tabindex to tabIndex
Lastly, if that doesn't help, to make your CSS work, ie .diabMetr + span + div, rewrite it to:
.diabMetr > span + div {}
or
.diabMetr > div {}
Right now, it's not selecting the child element.

How to add props in react for styles?

I have a simple section in which I want to change the width dynamically
Here is section
<div className="form-control">
<Formats>
{styles.map(style => <ButtonStyled type="button" active={style.id === styleId} onClick={() => setStyleId(style.id)} key={`button-${style.name}`}>{style.name}</ButtonStyled>)}
{activeStyle && <FormatsContent>
<FormatsDescription>{activeStyle.desciption}</FormatsDescription>
<Proportions>
{activeStyle.proportions.map(x => <Proportion onClick={() => setProportion(x.proportion)} active={proportion === x.proportion} width={x.width} height={x.height} key={`proportion-${x.proportion}`}>{x.proportionLabel}</Proportion>)}
</Proportions>
</FormatsContent>}
</Formats>
</div>
Here is style
const Formats = styled.div`
margin-left: 0px;
padding:12px;
background-color: ${gray.brightest};
border-radius: 20px;
width: 100%;
& select {
height: 31px;
padding: 0;
margin-left: 12px;
}
`;
Now I want to add props to check if width is full or not isFullWidth:true/false
and on styles to use it like this,
const Formats = styled.div`
margin-left: 0px;
padding:12px;
background-color: ${gray.brightest};
border-radius: 20px;
width: ${props => props.isFullWidth ? '100%' : '59%'}
& select {
height: 31px;
padding: 0;
margin-left: 12px;
}
`;
What do I need to change to achieve what I want?
The Format component should have isFullWidth prop holding either true or false as value as shown below:
The example below will give a 100% width
<Format isFullWidth ={true}>
</Format>
And this one will give a 59% width
<Format isFullWidth ={false}>
</Format>
I think it is enough to pass the prop to the component and keep the last style you posted:
So it should be
<Formats isFullWidth>
...
</Formats>
EDIT: wrong prop name

Lazy loading of images for website to load faster

i want that before the actual image gets loaded a spinner should be shown so that my website can load faster
window.addEventListener('load', function(){
var allimages= document.getElementsByTagName('img');
for (var i=0; i<allimages.length; i++) {
if (allimages[i].getAttribute('data-src')) {
allimages[i].setAttribute('src', allimages[i].getAttribute('data-src'));
}
}
}, false)
<img src="https://loremflickr.com/400/600" data-src="images/banguet-hall-location-icon.png" class="secEightImg" />
<img src="http://www.jettools.com/images/animated_spinner.gif" data-src="images/banguet-hall-location-icon.png" class="secEightImg" />
<script>
</script>
the problem is the actual image is shown two times and instead of spinner a broken image (which is shown when no image is found) is shown first
please help
If you want a spinner per image, just add the spinner URL as the initial src attribute for all of them:
<img src="spinner.gif" data-src="actual-image.png" />
Then, once the page loads, change all those src for the real URL (data-src) and listen for the load and error events on each image.
For each of them, add a .loaded class or .error class to the images and style them as you want. For example, you could hide the ones that could not be loaded, show a custom "error" image (using background-image) or style them as you wish, like in this example:
function imageLoaded(e) {
updateImage(e.target, 'loaded');
}
function imageError(e) {
updateImage(e.target, 'error');
}
function updateImage(img, classname) {
// Add the right class:
img.classList.add(classname);
// Remove the data-src attribute:
img.removeAttribute('data-src');
// Remove both listeners:
img.removeEventListener('load', imageLoaded);
img.removeEventListener('error', imageError);
}
window.addEventListener('load', () => {
Array.from(document.getElementsByTagName('img')).forEach(img => {
const src = img.getAttribute('data-src');
if (src) {
// Listen for both events:
img.addEventListener('load', imageLoaded);
img.addEventListener('error', imageError);
// Just to simulate a slow network:
setTimeout(() => {
img.setAttribute('src', src);
}, 2000 + Math.random() * 2000);
}
});
})
html,
body {
margin: 0;
height: 100%;
}
.images {
width: 100%;
height: 100%;
background: #000;
display: flex;
align-items: center;
overflow-x: scroll;
}
.margin-fix {
border-right: 1px solid transparent;
height: 16px;
}
img {
width: 16px;
height: 16px;
margin: 0 64px;
}
img.loaded {
width: auto;
height: 100%;
margin: 0;
}
img.error {
background: red;
border-radius: 100%;
/* You could add a custom "error" image here using background-image */
}
<div class="images">
<img
src="https://i.stack.imgur.com/RvfGz.gif"
data-src="https://d39a3h63xew422.cloudfront.net/wp-content/uploads/2014/07/20145029/driven-by-design-the-incomparable-lancia-stratos-1476934711918-1000x573.jpg" />
<img
src="https://i.stack.imgur.com/RvfGz.gif"
data-src="https://car-images.bauersecure.com/pagefiles/76591/1752x1168/ford_racing_puma_01.jpg?mode=max&quality=90&scale=down" />
<img
src="https://i.stack.imgur.com/RvfGz.gif"
data-src="http://doesntexist.com/image.jpg" />
<span class="margin-fix"></span>
</div>
The problem is that the spinner image you use initially might take some time to load.
One solution would be to use a data URI, so instead of:
<img src="https://i.stack.imgur.com/RvfGz.gif" data-src="actual-image.png" />
You would have:
<img src="data:image/gif;base64,R0lGODlhEAAQAPYAAAAAAP///yoqKmpqap6enr6+vrq6upCQkFxcXCIiIlpaWtra2tbW1s7OzsjIyMDAwJSUlEREROLi4oyMjBISEhAQEDw8PHR0dK6urqCgoEBAQC4uLsTExOjo6HJyclRUVKKiooKCghwcHHh4ePDw8JaWlmJiYpiYmEhISLi4uPT09E5OTmhoaObm5vj4+BYWFgoKCoaGhnp6eggICHx8fFZWVgQEBAICAj4+PjQ0NAYGBigoKFBQUA4ODiwsLBoaGiAgIDAwMDg4OEJCQh4eHiYmJgwMDCQkJISEhEpKSkxMTLKysqysrKSkpJycnLy8vMLCwjo6OoiIiMzMzBQUFNTU1HBwcKamptLS0uDg4F5eXrCwsOzs7HZ2dpqamsrKyjY2NjIyMhgYGEZGRoCAgGxsbGBgYKioqG5ubrS0tLa2ttzc3FhYWO7u7vLy8lJSUvr6+mRkZNjY2Orq6sbGxoqKitDQ0Pb29o6Ojt7e3qqqqpKSkn5+fgAAAAAAAAAAACH+GkNyZWF0ZWQgd2l0aCBhamF4bG9hZC5pbmZvACH5BAAKAAAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAEAAQAAAHjYAAgoOEhYUbIykthoUIHCQqLoI2OjeFCgsdJSsvgjcwPTaDAg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bWUvYWpheGxvYWQvd3d3L2xpYnJhaXJpZXMvY2xhc3MubXlzcWwucGhwPC9iPiBvbiBsaW5lIDxiPjY4PC9iPjxiciAvPgo8YnIgLz4KPGI+V2FybmluZzwvYj46ICBteXNxbF9xdWVyeSgpIFs8YSBocmVmPSdmdW5jdGlvbi5teXNxbC1xdWVyeSc+ZnVuY3Rpb24ubXlzcWwtcXVlcnk8L2E+XTogQSBsaW5rIHRvIHRoZSBzZXJ2ZXIgY291bGQgbm90IGJlIGVzdGFibGlzaGVkIGluIDxiPi9ob21lL2FqYXhsb2FkL3d3dy9saWJyYWlyaWVzL2NsYXNzLm15c3FsLnBocDwvYj4gb24gbGluZSA8Yj42ODwvYj48YnIgLz4K" data-src="actual-image.png" />
As you can see, your HTML document will grow fast using this approach, which is a problem.
A better approach might be to use CSS to add the spinner so that you only include the data URI once. To do that, you need to add an empty src attribute to your images initially anyway:
<img src data-src="actual-image.png" />
Or:
<img src="" data-src="actual-image.png" />
If you don't put it, the image will have an annoying gray border you can't get rid of until you add a src attribute.
function imageLoaded(e) {
updateImage(e.target, 'loaded');
}
function imageError(e) {
updateImage(e.target, 'error');
}
function updateImage(img, classname) {
// Add the right class:
img.classList.add(classname);
// Remove the data-src attribute:
img.removeAttribute('data-src');
// Remove both listeners:
img.removeEventListener('load', imageLoaded);
img.removeEventListener('error', imageError);
}
window.addEventListener('load', () => {
Array.from(document.getElementsByTagName('img')).forEach(img => {
const src = img.getAttribute('data-src');
if (src) {
// Listen for both events:
img.addEventListener('load', imageLoaded);
img.addEventListener('error', imageError);
// Just to simulate a slow network:
setTimeout(() => {
img.setAttribute('src', src);
}, 2000 + Math.random() * 2000);
}
});
})
html,
body {
margin: 0;
height: 100%;
}
.images {
width: 100%;
height: 100%;
background: #000;
display: flex;
align-items: center;
overflow-x: scroll;
}
.margin-fix {
border-right: 1px solid transparent;
height: 16px;
}
img {
width: 16px;
height: 16px;
margin: 0 64px;
background-image: url("data:image/gif;base64,R0lGODlhEAAQAP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0;
}
img.error {
background: red;
border-radius: 100%;
/* You could add a custom "error" image here using background-image */
}
<div class="images">
<img
src
data-src="https://d39a3h63xew422.cloudfront.net/wp-content/uploads/2014/07/20145029/driven-by-design-the-incomparable-lancia-stratos-1476934711918-1000x573.jpg" />
<img
src
data-src="https://car-images.bauersecure.com/pagefiles/76591/1752x1168/ford_racing_puma_01.jpg?mode=max&quality=90&scale=down" />
<img
src
data-src="http://doesntexist.com/image.jpg" />
<span class="margin-fix"></span>
</div>
Other approaches might be to just hide the images initially with display: none for example, in which case you might want a wrapper around them to show something like an empty box to indicate the users that something will be shown in there, or even a spinner made with other elements if you want/need to get fancy.
What you can do is something like:
$(".sly-main-slider div img").attr('src', "#");
$(".sly-main-slider").addClass("loading");
$(".sly-main-slider div").hide();
$(".sly-main-slider div img").load(function() {
$(".sly-main-slider div").show();
$(".sly-main-slider").removeClass("loading");
}).attr('src', "https://loremflickr.com/400/600");
.loading {
position: absolute;
top: 10%;
left: 10%;
z-index: 2000;
background: url(http://1.bp.blogspot.com/-nfXo9GWbDtM/VOn0vr4yLMI/AAAAAAAABCA/dDNgd7_QCFo/s1600/block-loader.gif) no-repeat center center;
height: 32px;
width: 32px;
}
.loading:after {
position: absolute;
top: 8px;
left: 40px;
content: 'Loading...';
}
body {
position: relative;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='sly-main-slider'>
<div>
<img src="https://loremflickr.com/400/600" alt="" />
</div>
</div>

Categories