Change output image size from JS - javascript

I have made an array with a set of random images which works. I just don't know how I'm supposed to style the image as an image;
var imageURLs = [
"./images/404/random1.png"
, "./images/404/random2.png"
, "./images/404/random3.png"
, "./images/404/random4.png"
, "./images/404/random5.png"
];
function getImageTag() {
var img = '<img src=\"';
var randomIndex = Math.floor(Math.random() * imageURLs.length);
img += imageURLs[randomIndex];
img += '\" alt=\"404 Image."/>';
img.className = "404image";
img.width = "10%"
return img;
}
document.write(getImageTag());
I'd assume you'd style it with the class name but I can't make .404image work for styling in CSS.
Any ideas? Thanks in advance, really stuck.

A CSS class name cannot start with a digit. If you name it image404 for instance it would be accessible with .image404
Edit: It is possible to use digit as first character in a class name if you escape it. I would still not recommend it since it causes a hassle and is against most naming standards in other languages.

One thing you can do to style create and style images as HTML elements with JS is this:
var fruit_pic = document.createElement("IMG")
fruit_pic.setAttribute("src", "https://melbournechapter.net/images/fruit-transparent-berry-6.png");
fruit_pic.setAttribute("width", "90");
fruit_pic.setAttribute("height", "60");
document.body.appendChild(fruit_pic);
body {
background-color: white;
text-align: center;
width: 450px;
margin: 0;
padding: 0;
}
p1 {
color: blue;
font-family: arial;
}
p2 {
color: blue;
font-family: arial;
}
p3 {
font-family: arial;
}
<body>
<h1>Fruit</h1>
</body>
I pulled this from this TryIt editor.
And also made a JSFiddle for it...

Use the Image() constructor.
var imageURLs = [
"./images/404/random1.png"
, "./images/404/random2.png"
, "./images/404/random3.png"
, "./images/404/random4.png"
, "./images/404/random5.png"
];
function getImageTag() {
var img = new Image();
var randomIndex = Math.floor(Math.random() * imageURLs.length);
img.src = imageURLs[randomIndex]
img.alt = '404 image';
img.style.width = '10%';
img.className = '404image';
return img;
}
document.body.appendChild(getImageTag());

Try this:
img += ' class="404image" width="10%"'; /* add line */
img += '\" alt=\"404 Image."/>';
img.className = "404image"; /* remove line */
img.width = "10%"; /* remove line */
P.S. String does not have className or width property. Also 404image is invalid as it cannot start with a digit.
var urls = ['https://4.bp.blogspot.com/-u0ld9dGuSD4/WmzFFRAJSlI/AAAAAAAABxY/IMoM6ckwf0csjBWMkBNVxPLZSZCMIvULwCLcBGAs/s1600/404-page-not-found-200.gif', 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQkuw1_2s5Ig8HtoQPV_qaP0AHeJzejhoeDDuW8u4VIYxslhYS1', 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQMUWkb3n7kAoqRDRe8wsEy3WqZlUaPkBH1MUWyahboi7buKUzd'];
document.querySelector('._404image').src = urls[Math.floor(Math.random() * urls.length)];
._404image {
margin: auto;
}
.container {
position: relative;
width: 80%;
text-align: center;
}
<div class="container">
<img class="_404image" />
</div>

Related

Code inside "hover" CSS selector stops working

I'm trying to create a small and interactive image gallery inside my page and everything besides this problem is working fine: When I mouse over the images they change opacity and size, as expected, however, after I click one of them and enlarge it, nothing happens when I try mousing over them again.
This is what I mean:
Current CSS:
#houseImages img {
opacity: 0.7;
margin: 1em;
transition: 0.3s;
width: 18em;
height: 15em;
border-radius: 3em;
border-style: solid;
border-width: 0.05em;
}
#houseImages img:hover {
transform: scale(1.1);
opacity: 1.0;
cursor: pointer;
}
Current script that is being used when an image is clicked:
"use strict";
function defaultSettings(imgElement)
{
imgElement.style.position = "initial";
imgElement.style.transform = "scale(1.0)";
imgElement.style.opacity = "0.7";
}
function clickedSettings(imgElement)
{
imgElement.style.position = "absolute";
imgElement.style.transform = "scale(2.6)";
imgElement.style.left = "40%";
imgElement.style.top = "30%";
imgElement.style.opacity = "1.0";
imgElement.style.zIndex = "99";
}
function imageClicked(imgID)
{
let img = document.getElementById("img" + imgID);
let otherImages = document.querySelectorAll("#houseImages img:not(#img" + imgID + ")");
let div = document.getElementById("houseImages");
let previousCloseImageButton = document.querySelector("#houseImages button");
// if another image was already clicked there's some cleanup to do
if(previousCloseImageButton)
previousCloseImageButton.remove();
otherImages.forEach(image => defaultSettings(image));
clickedSettings(img);
let closeImageButton = document.createElement('button');
closeImageButton.setAttribute("id","close");
closeImageButton.setAttribute("onclick","notClicked(" + imgID + ")");
closeImageButton.innerHTML = 'X';
div.append(closeImageButton);
}
function notClicked(imgID)
{
let img = document.getElementById("img" + imgID);
let closeImageButton = document.querySelector("#houseImages button");
defaultSettings(img);
closeImageButton.remove();
}
When you call defaultSettings(img); in the notClicked(imgID) function, you are setting a style property directly on the HTML img objects, as if you have written <img style="opacity: 0.7"> in HTML. Styles set on an object always have higher priority than those resulting from a stylesheet. In effect, rules defined for #houseImages img:hover cannot affect your image.
What you need to do is unset a local style property to let the stylesheet work again:
function defaultSettings(imgElement)
{
imgElement.style.position = "";
imgElement.style.transform = "";
imgElement.style.opacity = "";
}

DOM assign an id to child Javascript

I have created a grid with div, class and id. I want to randomly create a yellow square and I want to assign an id= 'yellowSquare' how do I do it?
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 100; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(99 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
drawPone.style.backgroundColor = 'yellow';
}
}
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
<div id="grid-box"></div>
I am new to Javascript / jQuery. Any help will be much appreciated ! Thank you
There are two options to your question. You can either change the id of the yellow square which is already created from your code, or create a child element within the square, which looks the same as your current solution. Creating a new child element will let you keep the numeric id pattern for the grid:
Changing the ID :
var element = document.getElementById('square' + randomIndex)
element.id = "yellowSquare";
Adding new element inside:
var node = document.createElement("DIV");
node.id = "yellowSquare";
node.style = "background-color:yellow;height:100%;width:100%;";
var element = document.getElementById('square' + randomIndex)
element.appendChild(node);
I set the styling of the div child to 100% width and height, as it has no content, and would get 0 values if nothing was specified. This should make it fill the parent container.
There are also multiple other ways to achieve the same result, for instance with JQuery.
Use the HTMLElement method setAttribute (source);
...
var drawPone = document.getElementById('square' + randomIndex);
drawPone.style.backgroundColor = 'yellow';
drawPone.setAttribute('id', 'yellowSquare');
...
As you requested in your comment how to move the square i made an example how you can move it left and right using jQuery next() and prev() functions. However because your html elements are 1 dimensional it's not easy to move them up/down and check the sides for collisions. Better would be to create your html table like with rows and columns and this way create a 2 dimensional play field.
Also added a yellowSquery class for selection with $drawPone.addClass('yellowSquare');.
Also since you like to use jQuery I changed your existing code to jQuery function. Might help you learn the framework.
var $grid = $("#grid-box");
for (var i = 1; i <= 100; i++) {
var $square = $("<div>");
$square.addClass('square');
$square.attr('id','square' + i);
$grid.append($square);
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(99 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var $drawPone = $('#square' + randomIndex);
$drawPone.addClass('yellowSquare');
}
}
$('#button_right').on('click', function(){
$yellowSquare = $('.yellowSquare')
$yellowSquareNext = $yellowSquare.next();
$yellowSquare.removeClass('yellowSquare');
$yellowSquareNext.addClass('yellowSquare');
});
$('#button_left').on('click', function(){
$yellowSquare = $('.yellowSquare')
$yellowSquarePrev = $yellowSquare.prev();
$yellowSquare.removeClass('yellowSquare');
$yellowSquarePrev.addClass('yellowSquare');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.yellowSquare {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="grid-box"></div>
<button id="button_left">left</button>
<button id="button_right">right</button><br>

For Loop not working and cloning Javascript

I've tried all sorts of things to figure out why my code isn't however, I can't seem to find out why. `
var numberOfFaces = 5;
var theleftside = document.getElementById ("leftSide");
var top_position = Math.floor((Math.random() * 400) + 1);
var left_position = Math.floor((Math.random() * 400) + 1);
var theRightSide = document.getElementById("rightSide");
function generatefaces () {
for (var i = 1; i < numberOfFaces; i++) {
var img = document.createElement("img");
img.src = "smile.png";
img.style.top = top_position + "px";
img.style.left = left_position + "px";
theleftside.appendChild(img);
}
}
<style media="screen">
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 2px solid black;
}
</style>
<h1>The Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
`
I am trying to generate 5 images (smiley faces) on the lefside div at different positions, then trying to clone it to the right hand side,
I'm new with JS, so hints and tips would be much appreciated.
Because you just implemented a function but did not call it. Try adding
generatefaces();
at the end.
Two fold firstly you need to, as burkay says, call the function generatefaces().
Secondly you need to create a second element for the right side using img.cloneNode(true) this creates a duplicate so you can then append that to the right side.
Also you are generating the random position outside of the loop so the same random position is used for each img you instead need to create a random position for every img by moving it inside the loop.
Example:
var numberOfFaces = 5;
var theleftside = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
// You need to call this function
generatefaces()
function generatefaces() {
for (var i = 1; i < numberOfFaces; i++) {
// Generate the new random position for each img
var top_position = Math.floor((Math.random() * 400) + 1);
var left_position = Math.floor((Math.random() * 400) + 1);
var img = document.createElement("img");
// The location of your face image
img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/54/Emojione_1F60E.svg/64px-Emojione_1F60E.svg.png";
img.style.top = top_position + "px";
img.style.left = left_position + "px";
// Creates a duplicate version of the image
var imgright = img.cloneNode(true);
theleftside.appendChild(img);
// Appends the duplicate image to the right side
theRightSide.appendChild(imgright);
}
}
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 2px solid black;
}
<h1>The Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
Hope this helps!

How to clone the contents of a div into another div with JavaScript?

I want to clone the images of the div leftSide into the div rightSide. On each click on the body the images on the left div should be cloned into the right div. But I can't get the result with the code I'm doing. Is there any mistake in my code? I want to use JavaScript.
Here's my code:
var theLeftSide = document.getElementById("leftSide");
var width = 500; var height = 500;
top_position = 0; var left_position = 0,
var numberOfFaces = 5;
var theRightSide = document.getElementById("rightSide");
var leftSideImages = theLeftSide.cloneNode(true);
document.getElementById("rightSide").appendChild(leftSideImages);
for (var i = 0; i < 5; i++) {
createElement(i);
numberOfFaces += 5;
function createElement() {
var image = document.createElement('img');
image.src = "smile.png";
image.style.position = 'absolute';
image.style.top = top_position + "px";
image.style.left = left_position + "px";
theLeftSide.appendChild(image);
top_position = Math.random() * 500 ;
left_position = Math.random() * 500 ;
Here is a simple example that clones an HTMLElement in vanilla javascript:
additional information can be found in MDN
function CloneCtrl() {
'use strict';
var self = this;
self.source = document.querySelector('.source');
self.target = document.querySelector('.target');
self.cloneSource = function(event) {
var clone = self.source.cloneNode(true);
self.target.appendChild(clone);
}
document
.getElementById('cloneBtn')
.addEventListener('click', self.cloneSource)
;
}
document.addEventListener('DOMContentLoaded', CloneCtrl);
.source {
background: lightseagreen;
width: 100px;
height: 100px;
line-height: 100px;
overflow: hidden;
margin: 5px;
display: inline-block;
text-align: center;
color: #fff;
}
.target {
border: 1px solid lightcoral;
min-height: 110px;
}
<div><button id="cloneBtn">Clone Source</button></div>
<div class="source">SOURCE</div>
<hr>
<div class="target"></div>
With jQuery, you can do it kike that:
$('#div2').html($('#div1').html());
which is found from this question: Copy the content of a div into another div.
You don't actually provide many details, thus the best I can post, hope it helps!!
you could simply try this if you have second div on page.
document.getElementById("SecondDv").innerHTML = document.getElementById("FirstDv").innerHTML;
This will copy whatever is there in FirstDiv to Second. lmk if it works.

setAttribute background-image can't be changed. Stuck at default value

function showHome() {
removeSlideShow();
var homeHeader = document.createElement("div");
homeHeader.setAttribute("id", "homeHeader");
document.getElementById("window").insertBefore(homeHeader, document.getElementById("content"));
var slideShowDiv = document.createElement("div");
var images = ["slideShow/slideShow-1.jpg", "slideShow/slideShow-2.jpg", "slideShow/slideShow-3.jpg", "slideShow/slideShow-4.jpg", "slideShow/slideShow-5.jpg", "slideShow/slideShow-6.jpg", "slideShow/slideShow-7.jpg"];
homeHeader.appendChild(slideShowDiv);
startSlideShow(slideShowDiv, images);
content.innerHTML = "";
}
function startSlideShow(element, images) {
var iterator = 0;
element.setAttribute("id", "slideShowDiv");
element.setAttribute("style", "background-image: url(" + images[0] + ")");
var startInterval = setInterval(function() {
iterator++;
if (iterator == images.length) iterator = 0;
element.setAttribute("style", "background-image: url(" + images[iterator] + ")");
element.style = "background-image: url(" + images[iterator] + ")";
transition(element);
}, 3000);
}
function removeSlideShow() {
if (document.getElementById("homeHeader")) {
document.getElementById("window").removeChild(document.getElementById("homeHeader"));
}
}
function transition(element) {
element.setAttribute("style", "opacity:0.01;");
var i = 0;
var set = setInterval(function() {
i += 0.01;
element.setAttribute("style", "opacity:" + i + ";");
}, 4);
setTimeout(function() {
clearInterval(set);
element.setAttribute("style", "opacity:1;");
}, 500);
}
div#homeHeader {
background-color: #FFF;
width: 900px;
height: 280px;
border: solid 2px #F00;
border-radius: 20px;
}
div#slideShowDiv {
background-image: url(slideShow/slideShow-1.jpg);
background-color: #FFF;
width: 898px;
height: 278px;
border: solid 1px #FFF;
border-radius: 20px;
background-size: 100% 100%;
}
What i want to do is change the background image every 3 seconds. The code work but it's not changing the image, stays at 'slideShow-1.jpg'. If i remove the transition(element); part, the image rotate just fine. What should i do to get it work? Im still beginner in Javascript, will learn jquery when i got better. Sorry for my grammar.
If i remove the transition(element); part, the image rotate just fine.
The transition part sets a new value for the style attribute.
Setting a new value for the attribute replaces the old value.
You are removing the style for the background image. (So the one from the stylesheet is applied again instead).
What should i do to get it work?
Don't use setAttribute(..., ...) to modify styles.
Use .style.cssPropertyName = ... instead.

Categories