How to check which background image div contains? - javascript

I have a div tag which can contain either 1 of the 3 images I have. Imagea, Imageb and ImageC as the background.
What I would like to do is write a if statement to check if background image the div contains.
var myDiv = document.getElementById("divtag1");
if(myDiv.style.backgroundImage == "url('images/plane.png')" ) {
// Doing something
}
This doesn't seem to work, any help is welcomed.

If you want to use JQuery
var background = $('.element').css('background-image')
if (background.indexOf("placehold.it/350x150") >= 0) {
$('.element').css('border', '5px solid black');
}
.element {
background-image: url('http://placehold.it/350x150');
width: 350px;
height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element"></div>

I have not tested this code so you may need to fiddle with it a bit but to check the background image you would do something like:
if (myDiv.style.backgroundImage == "url('images/plane.png')")
{
//DO SOMETHING.
}

You want the .style property. I don't think you'll need .getComputedStyle() but I'll link to that too.
So something like:
var myDiv = document.getElementById("divtag1");
if(myDiv.style.backgroundImage === "url('images/plane.png')" ) {
// Doing something
}

Here ye go. If you don't want to use regex, instead of if(imgtest.test(backgroundimage)) you can also use if(backgroundimage.indexOf('lion') > -1)
var lion = document.getElementById('lion');
var backgroundimage = window.getComputedStyle(lion).backgroundImage;
console.log(backgroundimage)
var imgtest = /lion/i; //regex to test for whatever string you need
if (imgtest.test(backgroundimage)) {
console.log("Yes, this is a lion.")
}
#lion {
background: url(http://www.slate.com/content/dam/slate/articles/health_and_science/science/2015/07/150730_SCI_Cecil_lion.jpg.CROP.promo-xlarge2.jpg);
background-size: contain;
width: 500px;
height: 357px;
}
<div id="lion"></div>

Related

add className on scroll in JavaScript

I'm trying to add a className on scroll. I keep getting a
document is undefined
edit: I found out I was getting the error from the typo. When I define document.getElementsByClassName("main-nav").scrollTop nothing comes up in the console. As well as the page does not get affected.
window.onscroll = function() {
windowScroll();
};
function windowScroll() {
if (document.getElementsByClassName("main-nav").scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementsByClassName("main-nav").className = "test";
} else {
document.getElementsByClassName("main-nav").className = "";
}
}
CSS is
.test {
background: pink
}
I'm not necessarily looking for the answer, I just want guidance
There are 2 problems:
getElementsByClassName returns an array of HTMLCollection and it has no property scrollTop. You probably want the first item so the code shoul be document.getElementsByClassName("main-nav")[0] (or document.querySelector(".main-nav"))
But if you try it, you will get an error:
Cannot read property 'scrollTop' of undefined
window.onscroll = function() {
windowScroll();
};
function windowScroll() {
if (document.getElementsByClassName("main-nav").scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementsByClassName("main-nav").className = "test";
} else {
document.getElementsByClassName("main-nav").className = "";
}
}
html, body {
height: 150%;
}
.test {
background: pink
}
<div class="main-nav"></div>
The reason is that you override the class attribute of .main-nav by this assignment:
document.getElementsByClassName("main-nav").className = "";
In this line you set the class attribute to empty string. You probably want to add / remove the test call but keeping the main-nav class.
There are 2 things you can do:
Set the id attribute to main-nav instead of the class attribute, then use document.getElementById method.
window.onscroll = function() {
windowScroll();
};
function windowScroll() {
if (document.getElementById("main-nav").scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementById("main-nav").className = "test";
} else {
document.getElementById("main-nav").className = "";
}
}
html, body {
height: 150%;
}
#main-nav {
position: fixed;
width: 100%;
}
.test {
background: pink
}
<div id="main-nav">Main Nav</div>
Toggle only the test class using classList.toggle.
window.onscroll = function() {
windowScroll();
};
function windowScroll() {
if (document.getElementsByClassName("main-nav")[0].scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementsByClassName("main-nav")[0].classList.add("test");
} else {
document.getElementsByClassName("main-nav")[0].classList.remove("test");
}
}
html, body {
height: 150%;
}
.main-nav {
position: fixed;
width: 100%;
}
.test {
background: pink
}
<div class="main-nav">Main Nav</div>
The final approach with some optimisations:
var mainNav = document.querySelector('.main-nav');
window.onscroll = function() {
windowScroll();
};
function windowScroll() {
mainNav.classList.toggle("test", mainNav.scrollTop > 50 || document.documentElement.scrollTop > 50);
}
html, body {
height: 150%;
}
.main-nav {
position: fixed;
width: 100%;
}
.test {
background: pink
}
<div class="main-nav">Main Nav</div>
The changes:
Store the .main-nav element on the global context (the window object). It will not change so you don't need to find it in any scroll.
Use querySelector so you will get a single DOM element, not collection.
Use classList.toggle to toggle the class by condition.
The issue with your console.log is that you're trying to pull the scrollTop for an HTML Collection (a collection of elements in your page) of 1 or more divs - therefore it can't check for the scrollTop as the console.log as it doesn't actually have that property.
Assuming you only have one element with the "main-nav" class (or there is a particular element with this class that you wish to apply it to), you would be better off using one of the following: document.getElementsByClassName("main-nav")[0] or document.getElementById("main-nav") (the latter would require you to create a main-nav id rather than a class).
For the first one, however, using className reassigns the class name rather than adding to that particular div, therefore you can use document.getElementsByClassName("main-nav")[0].classList.add("test") (and remove instead of add if it does not match your criteria).
If there is more than one element with the "main-nav" class, you can still use the first option I suggested - only you would need to wrap it around in a for loop and replace the 0 with your variable of choice.
for (i = 0; i < document.getElementsByClassName("main-nav").length; i++) {
//your code here using document.getElementsByClassName("main-nav")[i]
}

Display some element user scrolling

I would like to display some element (div for example) when the user scrolling.
I seeing that a scrollTop, but isn't work. Because for sure I use badly.
I can't find some help without JQuery. I don't want to use JQuery.
I try this :
var scroll = document.body.scrollTop;
var divLis = document.querySelectorAll("div");
for(let i = 0; i < divLis.length; i++) {
if(scroll === divLis[i]) {
divLis[i].style.transform = "translateX(0)";
divLis[i].style.transition = "2s";
}
}
I honestly can't really tell what you're trying to do, but given your response to #uom-pgregorio's answer, I'm guessing you might just want a pure JS scroll listener:
window.addEventListener('scroll', function() {});
Edit: Sorry I just noticed that you didn't want jQuery but I'll just leave this here in case you change your mind.
$(window).scroll(function() {
// show the div(s)
});
That's an event handler where the function runs or fires up whenever the window or viewport scrolls.
Ok... I understand.
I wanted to try this :
* {
margin: 0;
padding: 0;
border: 0;
}
body {
height: 200vh;
}
.left {
width: 300px;
height: 300px;
background-color: red;
position: absolute;
top: 150%;
transform: translateX(-300px);
transition: 5s;
}
// HTML :
<div class="left"></div>
// JS
var divLis = document.querySelector(".left");
window.addEventListener("scroll", function (e) {
if(window.pageYOffset > 500) {
console.log(window.pageYOffset)
divLis.style.transform = "translateX(0)";
}
})
So, it's very simple and I took my head for nothing.
So thanks so much for answering me !
Enjoy your Weekend

Unable to remove gray borders around images?

For some reason, I am unable to remove a gray border from around my images. I am using Javascript to insert them, if that helps you. Thanks!
var helloContainer = document.getElementById('hello-container');
var helloImg = new Image(20, 20);
function imgRepeater(e) {
var helloCount = e;
helloImg.className = 'hello-img';
helloContainer.innerHTML = '';
if (e != "0") {
for (var i = 0; i < helloCount; i++) {
helloContainer.appendChild(helloImg.cloneNode(true));
}
}
}
imgRepeater(10);
.hello-img {
width: 20pt;
height: 20pt;
background-image: url("http://emojipedia-us.s3.amazonaws.com/cache/1a/01/1a010db8ee92e120595b5b8977a8328e.png");
background-size: contain;
border: 0 !important;
outline: 0 !important;
}
<div id="hello-container"></div>
It's caused because the image element requires a "src" attribute. The grey border is part of the placeholder that the browser will display in place of the image. To remove it you should either set the "src" attribute of the image instead of applying it with CSS, or create a different element such as a span.
It looks like your container (helloContainer) is the element with the grey background. Right-click on the element and use 'Inspect Element' to look at the active CSS.

Attempting to get dynamically generated classes to loop

I have a script which is dynamically adding a class every time the user moves their mouse in/out of the box (whenever they do, it makes the box larger). I am hoping to make this process loop, so that the large box goes back to a small box. I have attempted to use a if statement to check if the box has the class of "large" then it will revert the class back to "small" in the hopes that the document would repeat itself. Didnt work. Can you suggest any way of achieving this using similar code? I would hope to get this to work with 4 separate classes. Fiddle here: http://jsfiddle.net/cs31g61q/1/
var container=$("#container");
var box=$("#box");
box.mouseenter(function(){
$('#box').removeClass("small");
$('#box').addClass("medium");
});
box.mouseleave(function(){
container.on("mouseenter", "#box", function(){
$(this).removeClass("medium");
$(this).addClass("large");
});
});
<div id="container">
<div id="box" class="small">
</div>
</div>
Does the below snippet produce your desired result?
Snippet:
var box = $('#box');
var classes = ['small', 'medium', 'large'];
var iterator = 0;
box.mouseenter(function () {
$(this).removeClass();
$(this).addClass(classes[iterator]);
iterator += 1;
iterator = iterator > classes.length - 1 ? 0 : iterator;
});
.small {
width: 100px;
height:100px;
background: #000;
}
.medium {
width: 200px;
height: 200px;
background: green;
}
.large {
width:400px;
height: 400px;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="container">
<div id="box" class="small"></div>
</div>
This is basically iterating through a set of classes, applying them one by one on every single time mouse enters #box.
Hope this helps.
Fiddle here.
Check your logic: you only need one event listener - it should respond to either mouseenter or mouseleave and cycle through the classes (small, medium, large).
Below is a very simple approach, as demonstrated in the Fiddle above.
// Set up the event listener: every mouseenter or mouseleave
$(document).on('mouseenter mouseleave', "#box", function(){
var currentClass = $('#box').attr("class");
var newClass = ''; // TBD in switch statement.
switch(currentClass) {
case('small'):
newClass = 'medium';
break;
case('medium'):
newClass = 'large';
break;
case('large'):
default:
newClass = 'small';
break;
}
// Remove the current class, add new one.
$('#box').removeClass();
$('#box').addClass(newClass);
});

Change CSS with Jquery and JS

I try to change the size of image via JS function.
I have table with Images, and I want that if the user click on Image her size will change to 400,400 , and all the other image will set to the default 100,100.
I make OnClick event for every image in the table that operate the next function:
function ChangeSize(it) {
$('td img not(it)' ).css({"width":"100","height":"100"});
if (it.width == 100)
{
it.width = 400;
it.height=400;
}
else
{
it.width = 100;
it.height=100;
}
}
I know that my Jquery not work. but How Can I do that?
thank you!
If it is an DOMElement:
$('td img not(it)') is an invalid selector, use $('td img').not(it)
A much better way to achieve this is to set the 100x100 size as default size and to apply a class on the clicked one:
td img {
width: 100px;
height: 100px;
}
img.selected {
width: 400px;
height: 400px;
}
function ChangeSize(it) {
$('td img').removeClass('selected');
$(it).addClass('selected');
}
Not tested:
function ChangeSize(it) {
$('td img').css({"width":"100", "height":"100"});
$(it).css({"width":"400", "height":"400"});
}
rather, use:
function ChangeSize(it) {
$('td img').not(it).css({"width":"100px",
"height":"100px"});
if (parseInt(it.width) == 100)
{it.width = 400+'px';
it.height=400+'px';}
else
{it.width = 100+'px';
it.height=100+'px';}
}
I hope this fixes the bug

Categories

Resources