So I do have a profile image in my project, and I want it to have a green border. But everytime I reload the page, the image dissapears for a short moment, but to border still remains. I wanted to ask if there is any way, maybe with JavaScript to remove the border-element in css if the image is not loaded yet
This is my html:
<img src="somepic.png" id="user_img" >
and this is my css:
.user_img{
border: 2px solid rgb(136, 186, 60);
}
I already tried this with jquery:
if(!$("#user_img").complete){
$("#user_img").removeClass("user_img")
}
But this doesn't really work dynamically, so the border would just dissapear forever. Is there any way to check on reload and only add the border if the image is fully loaded?
CodePudding user response:
Try to add border with js
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style2.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" />
</head>
<body>
<img src="https://picsum.photos/id/237/200/300" id="user_img" >
</body>
</html>
js
<script>
$(document).ready(function(){
document.getElementById("user_img").style.border = "2px solid rgb(136, 186, 60)";
});
</script>
CodePudding user response:
Set default border:none
, create class with border style and add it by JS after load.
const userImage = document.getElementById('user_img');
if (userImage.complete) {
// add class if loaded yet
userImage.classList.add('add-border')
} else {
// wait load in otherwise
userImage.addEventListener('load', () => userImage.classList.add('add-border'))
}
#userImg {
/* no border here */
}
.add-border {
border: 2px solid rgb(136, 186, 60);
}
CodePudding user response:
You can use a bit of Javascript to handle this.
function myFunction(e) {
e.classList.add("user_img");
}
.user_img {
border: 2px solid rgb(136, 186, 60);
}
<img src="somepic.png" id="user_img"
onload="javascript: myFunction(this)"
onerror="javascript: alert('The image has failed to load')" />
<img src="https://t4.ftcdn.net/jpg/02/29/75/83/360_F_229758328_7x8jwCwjtBMmC6rgFzLFhZoEpLobB6L8.jpg" id="user_img2"
onload="javascript: myFunction(this)"
onerror="javascript: alert('The image has failed to load')" />