How to add multiple div inside single div with horizontal scroll? - javascript

I am trying to add multiple div inside a single div with horizontal scroll.
This is my code:
<div id="scrollimages">
<script>
var container = document.getElementById("scrollimages");
var array=["img/screen2.png","img/logo.png"];
for(var i=0;i<array.length;i++)
{
var src="url("+array[i]+")";
// var inside = '<div class="block" style="background-image: { ' + src + ' }"></div>';
var inside = '<div class="blocks"></div>'
inside.style.backgroundImage=src;
inside.style.marginLeft=100*i+"%";
container.innerHTML +=inside;
}
</script>
</div>
This is my css code:
#scrollimages {
background-color: #00FFFF;
width: 100%;
margin-left:0px;
height: 150px;
overflow: scroll;
white-space:normal;
overflow-y:none;
margin-top:20px;
}
.blocks
{
height: 100%;
width: 100%
margin-left:0px;
word-wrap:normal;
}
First time i am using java script and css all ,so i can't get this easy step .help me out this problem.
what mistake i made,

The same #id can only be once in a document.
var inside = '<div id="block"></div>'
Use a class instead
var inside = '<div class="block"></div>'
and in CSS
.block { ...
Also, much easier, to add the attributes directly to the string
var inside = '<div class="block" style="background-image:'+ src +'"></div>';
Edit: fixed remove {} in style.
Edit: There were some other problems in the script, here is a working jsfiddle: https://jsfiddle.net/C14L/9hnqheos/

Add Flex property to the container, also keep overflow auto. If using Flex no need to use white-space.
#scrollimages {
display: flex;
overflow: auto;
}

Instead of attaching background to div I am creating img & appending it inside the div.
Also
Hope this will be useful
JS
var container = document.getElementById("scrollimages");
var myArray=[image urls];
for(var i=0;i < myArray.length;i++){
var _createElem = document.createElement('div');
var _img = document.createElement('img')
_img.src = myArray[i]
_createElem.id ="block_"+i;
_createElem.appendChild(_img)
_createElem.className = "block";
container.appendChild(_createElem);
}
CSS
#scrollimages {
background-color: #00FFFF;
width: 100%;
margin-left:0px;
overflow-x:scroll;
margin-top:20px;
}
.block{
width:auto;
display:table-cell;
height: 100%;
}
you can make further changes if it required
Demo

As per C14L, need to assign class, and since you're using getElementByID, each element should be assigned a seperate ID.
In the below JS Fiddle, I've swapped backgroundImage for backgroundColor, and removed your margin code (not sure what you were attempted here, but you had 100% margin on the 2nd iteration, 200% for the third... Don't think thats what you had in mind... For demo purposes, height of 'block' was set to 30px instead of 100% since divs have no height by default...
https://jsfiddle.net/7mua0rez/
var container = document.getElementById("scrollimages");
var array=["red","green", "black"];
for(var i=0;i<array.length;i++)
{
var src=array[i];
var inside = '<div id="block' + i + '" class="block"></div>'
container.innerHTML +=inside;
document.getElementById("block" + i).style.backgroundColor=src;
document.getElementById("block" +i).style.marginLeft=10+"%";
}

Related

How do I dynamically create + insert (append??) a div into a div container?

I would like it to end up as this:
<div id = "container">
<div id = "dynamicallyCreated"></div>
</div>
I'm pretty sure that this involves either document.createElement or appendChild, but I am not quite sure how to use these to insert the newly created div into the container div.
Edit: sorry, I'm not quite sure how to do the code snippet correctly
I'm pretty sure that this involves either document.createElement or appendChild
Both, actually: :-)
const div = document.createElement("div");
div.id = "dynamicallyCreated";
document.getElementById("container").appendChild(div);
More to explore on MDN: createElement, appendChild
You can also use markup if you prefer via insertAdjacentHTML:
document.getElementById("container").insertAdjacentHTML(
"beforeend",
"<div id='dynamicallyCreated'></div>"
);
It can add text in front of, after, at the beginning of, or at the end of an element. (Or if adding text, insertAdjacentText.)
If adding not at the end of the container, you can use insertBefore.
This is how you can do it :
Create element using document.createElement()
Add attributes (if you wish)
Append it to the parent element, using appendChild().
var newEl = document.createElement('div');
newEl.setAttribute("id", "newElement");
document.querySelector("#container").appendChild(newEl);
#container {
width: 100px;
height: 100px;
background: red;
}
#newElement {
width: 50px;
height: 50px;
background: yellow;
}
<div id="container">
</div>
Another approach for the same can be done using innerHTML property :
document.querySelector('#container').innerHTML = "<div id='newElement'></div>"
#container {
width: 100px;
height: 100px;
background: red;
}
#newElement {
width: 50px;
height: 50px;
background: yellow;
}
<div id="container">
</div>

Change image opacity when using GetElementById

Part of my Uni module requires me to make a webstory that uses random elements to mix up the story. I'm using GetElementById in JS to embed one random image from an array into a div, which works perfectly fine. The image becomes the background of the div, and I then have text on top of the image - again this all works perfectly fine.
However the issue is that I want the image to be slightly transparent so that the text is easier to read, however no matter what solution I try, I can't get it to work.
I've tried making the div transparent in both CSS and JS, however then the whole div including the text is effected which defeats the point. Then when I try the RGBA style in CSS, the image isn't effected.
So what I need is the image that is loaded into the div through JS to be slightly transparent, whilst the text that is also in the div in the HTML doument to remain untouched.
This is the JS I'm using to randomly select an image:
function randomGun() {
var imgCount = 3;
var dir = 'img/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = new Array
images[1] = "gun1.jpg",
images[2] = "gun2.jpg",
images[3] = "gun3.jpg",
document.getElementById("left").style.backgroundImage = "url(" + dir + images[randomCount] + ")";
}
<div id="container">
<div id="left">
<a id="message">Drive a bit closer to see if anybody is there.</a>
</div>
<script>
window.onload = randomGun()
</script>
</div>
Use a nested div with semi-transparent white background.
<div id="container">
<div id="left">
<div id="nested" style="width:100%;height:100%; background-color: rgba(255,255,255,0.5)">
<a id="message">Drive a bit closer to see if anybody is there.</a>
</div>
</div>
<script>window.onload = randomGun()</script>
</div>
In addition, I would set everything relative to style in a stylesheet, or at least inside a <style></style>.
UPDATE
Added your JS and fixed it a little. Note the adjustment to the random expression.
Perhaps this'll help you.
Use an element that'll contain 2 other elements, give the container position:relative and z-index:-2
Then the 2 elements inside should have position:absolute.
Next give the top element z-index:-1, background:url(http://image-host.com/path/to/img.jpg), and opacity:.5
Then the second element should have text and whatever else you want visible. Give this element z-index:1.
The reason why opacity wasn't working the way you expected to work is because opacity applies to everything within the element as well. Here in the Snippet, we layered an element with content and an element with a background image separately.
REFERENCE: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index
SNIPPET
function randomBG() {
var imgCount = 3;
var path = 'http://imgh.us/';
var randomCount = Math.round(Math.random() * (imgCount));
var images = ['solar_system.jpg', 'kowloon.jpg', 'transparent-map.png'];
document.getElementById("fader").style.backgroundImage = "url(" + path + images[randomCount] + ")";
}
window.onload = randomBG;
html,
body {
height: 100%;
width: 100%;
font: 400 16px/1.5 Verdana;
box-sizing: border-box;
}
* {
margin: 0;
padding: 0;
border: 0;
}
#base {
position: relative;
z-index: -2;
width: 100vw;
height: 100vh;
}
#content {
position: absolute;
z-index: 1;
padding: 20px;
margin: 0 auto;
width: 75%;
height: auto;
top: 0;
left: 0;
background: none;
}
#fader {
position: absolute;
z-index: -1;
padding: 20px;
margin: 0 auto;
min-width: 75%;
min-height: 75%;
/*background: url(http://imgh.us/Lenna.png);*/
opacity: .5;
}
<main id='base'>
<section id='fader'></section>
<article id='content'>
<h1>This is the Text</h1>
</article>
</main>

How to create a grid of elements (divs/spans) in perfect squares with their backgrounds set to images

I've been working on a website that serves as a gallery for fantasy art, an evolving project, and I've currently hit a barricade in where to go from something I can't get to work. I tried Masonry and Wookmark both, and had issues with both, so I'm trying to do something else. I'm wanting to spawn in either divs or spans (I'm not sure which to use) within grid with the class identifier images and set their backgrounds to specific image sources that "cover", centered, so I basically have a grid of square windows into these images and when clicked, they bring up a lightbox (which I've succesfully created). Right now I've managed to get the images to show but the containers are smooshed down and have no padding left or right.
Truth be told, I have no idea what to do with the relative/absolute positioning and inline/block display parameters, and I feel this is where I'm going wrong but I don't know really what these things entail.
Segment of the HTML:
<div id="grid" class="grid"></div>
<br>
CSS:
.grid {
z-index:2;
display: inline-block;
}
.images {
display:inline-block;
position:relative;
width:25%;
height:25%;
z-index:2;
padding-right: 0.25em;
padding-left: 0.25em;
padding-top: 0.5em;
background-size: cover;
background-attachment: fixed;
background-repeat: no-repeat;
background-position: center;
}
Javascript:
var mix = shuffle(Object.keys(backInfo));
function unlockImages () {
setTimeout(function () {
if (mix !== undefined) {
var input = mix.shift();
var entry = backInfo[input];
var elem = document.createElement("div");
elem.setAttribute("class", "images");
elem.setAttribute("id", input);
elem.setAttribute("title", entry.caption);
elem.setAttribute("onclick", "javascript:changeImage(" + input + ");");
document.getElementById("grid").appendChild(elem);
document.getElementById(input).style.backgroundImage = "url(" + entry.image + ")";
$("#" + input).fadeTo(0,0);
$("#" + input).fadeTo(20000,1);
unlockImages();
}
}, 0)
}
And a live preview of what's going on at the moment: http://www.dreamquest.io
I think the problem you are describing is css. I played with your css a little and came up with this:
.grid {
z-index:2;
display: inline-block;
height: 500px;
width: 1500px;
}
.images {
display:inline-block;
position:relative;
width:25%;
height:25%;
z-index:2;
margin-right: 0.25em;
margin-left: 0.25em;
margin-top: 0.5em;
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
Some things to note with your css:
when you are setting a percentage width x height, your parent container has to have a value. Since you didn't set a height value in the .grid class your images get squished because it is taking 25% of 0 height.
background-attachment: fixed; forces your picture not to auto resize, which i am assuming you want
you were using padding that is why you are not getting the spacing between images. Padding is for the interior of the element. If you want space between elements then you need to use margin, which I have used in the above css. hth
I assume that you want to create dynamic grid and populate images for each box. Use below code to achieve it.
create container div with id "wrapper".
Add Javascript function and called it where ever you want.
function DrawGrid() {
var rows = 2;
var columns = 2;
$("#wrapper").empty();
for (var i = 0; i < rows; i++) {
var $row = $("<div />", {
class: 'row'
});
//add columns to the the temp row object
for (var c = 0; c < columns; c++) {
var $square = $("<div />", {
class: 'square'
});
//Set your imageHere
$square.append("<img></img>");
$row.append($square.clone());
}
$("#wrapper").append($row.clone());
}
}

How to get margin left size using javascript when I use margin auto property in css

I have div with margin:auto; and I need get only margin-left size value using javascript :)
//css
.test{
margin: auto;
width: 100px;
height: 100px;
outline: 1px solid red;
}
// html
<div class="test">Test</div>
Live example
Use this:
1) With jQuery
var left = $(".test").offset().left;
2) Or, second version is that:
Replace your div to <div class="test" id="test"></div>, and use this js.
var left = document.getElementById("test").offsetLeft;
You can use window.getComputedStyle() method if you don't need IE8 support.
var test = document.querySelector('.test');
var left_margin = window.getComputedStyle(test).getPropertyValue("margin-left"); // returns margin e.g. '655px'
left_margin = left_margin.match(/\d+/); //returns bare number e.g. '655'
You don't need jQuery for that, plain JavaScript is enough:
var left, element = document.querySelector('.test');
if(element) {
left = element.getBoundingClientRect().left;
}

How can I apply an existing CSS class style to a dynamically created div?

Apologies for this seemingly redundant question, but the others all seem to be asking about different cases, such as using JQuery. I'm trying to dynamically create a div & apply an existing CSS style to it, but the div isn't taking on the style. Any tips are much appreciated:
<style>
div.tile {
position: absolute;
overflow: hidden;
background: rgba(1,1,0,1);
width: 400px;
height: 400px;
}
.a { left: 2cm; top: 2cm; z-index: 1; }
.b { left: 4cm; top: 4cm; z-index: 2; }
</style>
</head>
<body>
<script type="text/javascript">
createLayer(1);
function createLayer(layerIndex){
var div = document.createElement('div');
div.id = "div"+layerIndex;
div.class = "tile a";
document.body.appendChild(div);
var canvas = document.createElement('canvas');
canvas.id = "layer" + layerIndex;
div.appendChild(canvas);
}
In vanilla JS the property for adding a class to an element is className not class.
Try this instead:
div.className = "tile a";
What you should do is inspect the HTML after your function has run to make sure that the class is being applied properly. The CSS will apply to the matching element even if it is dynamically created - unless the element isn't being tagged correctly. I suggest using Firebug in Firefox to make sure that your div is correct.

Categories

Resources