JavaScript Image (how to set height and width, using document.getElementById().src=' ') - javascript

How do I set the Bush picture to 100px by 100px?
<!DOCTYE html>
<html>
<head>
<title> Title </title>
<script>
</script>
</head>
<body>
<button type = button onclick = "document.getElementById('myImage').src='bush.jpg'">Bush</button>
<button type = button onclick = "document.getElementById('myImage').src='obama.jpg'">Obama</button>
<p>Default is Obama </p>
<img id = "myImage" src = "obama.jpg" style = "width: 100px; height: 100px">
</body>
</html>
I am in the beginning phase of learning javascript. Not sure what other information is really needed. I'm just trying to get a job in full-stack web development and realized there's less jobs in what I learned in school (Java/C/C++). I know it's a relatively simple question but don't know how to google the answer either since I don't know how to phrase the question... ha... anyone with some decent experience know how to do this?

Your style attribute is has invalid information in it. Your image tag looks like this:
<img id = "myImage" src = "obama.jpg" style = "width: 100px height: 100px">
and it should look like this:
<img id = "myImage" src = "obama.jpg" style = "width: 100px; height: 100px;">
Notice the added ;
Here is an example of setting style on the image dynamically. I used a function to switch the images.
<button type = button onclick = "changeImage('bush');">Bush</button>
<button type = button onclick = "changeImage('obama')">Obama</button>
<p>Default is Obama </p>
<img id = "myImage" src = "https://whitehouse.gov1.info/photos_obama_face/obama-happy-flag.jpg" style = "width: 100px; height: 100px" />
<script>
function changeImage(chump) {
var img = document.getElementById('myImage');
if(chump === 'obama') {
img.src = 'https://whitehouse.gov1.info/photos_obama_face/obama-happy-flag.jpg';
img.style.width = '100px';
img.style.height = '100px';
}
else {
img.src = 'http://www.capitolhillblue.com/wp-content/uploads/2011/07/071511bush.jpg';
img.style.width = '200px';
img.style.height = '200px';
}
}
</script>

Related

Set width and height for image random by Javascript

Something hard to understand for me that, how can I set width and height for the random images when they displayed. Can anyone help me, please?
This is my code
function randomImage(){
var imagesArray = ['images/person1.jpg', 'images/person2.jpg', 'images/person3.jpg'];
var num = Math.floor(Math.random() * 3);
document.canvas.src = imagesArray[num];
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display random image</title>
</head>
<body>
<input type="button" id="randomImage" onclick="randomImage()" value="Random">
<img src="" name="canvas" />
</body>
</html>
And I do not know how to set width and height so I did not write code for this yet, this code just display images random when I click button
Your help is my pleasure
To identify your image by name attribute, use getElementsByName or the newer querySelector and for setting width and height you can use style attribute:
document.getElementsByName("canvas")[0].src = imagesArray[num];
or
document.querySelector("img[name=canvas]").src = imagesArray[num];
and for width and height (you can also use querySelector here):
document.getElementsByName("canvas")[0].style.width = "100px";
document.getElementsByName("canvas")[0].style.height= "100px";
function randomImage(){
let imagesArray = ['images/person1.jpg', 'images/person2.jpg', 'images/person3.jpg'];
let num = Math.floor(Math.random() * 3);
let image = document.getElementsByName("canvas")[0];
image.src = imagesArray[num];
image.style.width = "100px";
image.style.height = "100px";
}
<input type="button" id="randomImage" onclick="randomImage()" value="Random">
<img src="" name="canvas" />
if you want a random value for width and height, use it instead of the 100 in my sample
You should create a class: "image"
and in CSS you should add:
.image{
width: 220px; // you put your value here
height: auto; // to considere the proportions of the image
}
I am notsure if this answers your question, but you can also choose other approach you can do as following:
<div class="wrapper">
<img>
</div>
where .wrapper has overflow set to hidden and img has width of 100% and height auto,
You could've used window.canvas here, but that's not advisable. To retrieve one element, document.querySelector is your friend.
randomImage();
document.addEventListener("click", evt => {
if (evt.target.nodeName === "BUTTON") {
randomImage();
}
});
function randomImage() {
const imagesArray = [
'https://picsum.photos/200/300',
'https://picsum.photos/300/400',
'https://picsum.photos/100/100'
];
const randomNumber = Math.floor(Math.random() * 3);
document.querySelector("img[name='canvas']").src = imagesArray[randomNumber];
}
button {
float: right;
position: fixed;
right: 30vw;
top: 1rem;
}
<img name="canvas" src="" />
<br><button>Another picture</button>

Javascript : add images in div upon selecting value from select box

I am trying too add image inside dynamically created div. When user create go button it should create div element and image inside it according to value selected in select box. I have created div tag dynamically and created image object in order to get image. but in my code image is not loading inside div. can anyone help me to figure out issue ?
CSS
<style>
body{
background-image: url("final_images/back.jpg");
}
.container{
/*width: 600px;*/
/*height: 200px;*/
border:inset;
margin-top: 100px;
margin-left: 300px;
margin-right: 190px;
background-color:rgba(255, 234, 134, 0.9);
}
#selectBox{
margin-left: 210px;
width: 160px;
}
#holder {
width: 300px;
height: 300px;
background-color: #ffffff;
}
</style>
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class = 'container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
<option value="womens">Women's coat</option>
<option value="mens">Men's coat</option>
<option value="kids">Kid's toys</option>
<option value="mixture">Classic mixture</option>
<option value="earing">Gold Earing</option>
</select>
<INPUT TYPE="button" VALUE="Go" id="go">
</INPUT>
</form>
<HR size="4" color="red" id="hr">
<!-- <div id="holder"> </div> -->
</div>
</body>
</html>
Javascript
<script>
imageObj = new Image(128, 128);
// set image list
images = new Array();
images[0]="final_images/wcoat.jpg";
images[1]="final_images/wcoat.jpg";
var go = document.getElementById('go');
go.addEventListener("click", loadItem);
function loadItem() {
var mainDiv = document.getElementById("main");
var btnPre = document.createElement("input");
//Assign different attributes to the element.
btnPre.type = "button";
btnPre.value = "previous";
btnPre.id = "preBtn";
mainDiv.appendChild(btnPre);
newdiv = document.createElement('div'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv); //add an id
var btnNxt = document.createElement("input");
//Assign different attributes to the element.
btnNxt.type = "button";
btnNxt.value = "next";
btnNxt.id = "nxtBtn";
mainDiv.appendChild(btnNxt);
var holder = document.getElementById("holder");
if(document.getElementById('selectBox').value == "womens"){
holder.src = images[0] + " Women's coat";
}
else if(document.getElementById('selectBox').value == "mens"){
holder.src = images[1] + " Men's coat";
}
}
</script>
A div is not an image container. Replace with img in the createElement fixes this.
Another big problem is the margins you use.
I've made a few adjustments
replaced margin-left with float: right for the select
put margin auto for left and right on the box.
imageObj = new Image(128, 128);
// set image list
images = new Array();
images[0] = "final_images/wcoat.jpg";
images[1] = "final_images/wcoat.jpg";
var go = document.getElementById('go');
go.addEventListener("click", loadItem);
function loadItem() {
var mainDiv = document.getElementById("main");
var btnPre = document.createElement("input");
//Assign different attributes to the element.
btnPre.type = "button";
btnPre.value = "previous";
btnPre.id = "preBtn";
mainDiv.appendChild(btnPre);
newdiv = document.createElement('img'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv); //add an id
var btnNxt = document.createElement("input");
//Assign different attributes to the element.
btnNxt.type = "button";
btnNxt.value = "next";
btnNxt.id = "nxtBtn";
mainDiv.appendChild(btnNxt);
var holder = document.getElementById("holder");
if (document.getElementById('selectBox').value == "womens") {
holder.src = images[0] + " Women's coat";
} else if (document.getElementById('selectBox').value == "mens") {
holder.src = images[1] + " Men's coat";
}
}
body {
background-image: url("final_images/back.jpg");
}
* {
box-sizing: border-box;
}
.container {
width: 400px;
border: inset;
margin-top: 100px;
margin-left: auto;
margin-right: auto;
background-color: rgba(255, 234, 134, 0.9);
}
#selectBox {
float: right;
width: 160px;
}
#holder {
width: 300px;
height: 300px;
background-color: #ffffff;
}
<div class='container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
<option value="womens">Women's coat</option>
<option value="mens">Men's coat</option>
<option value="kids">Kid's toys</option>
<option value="mixture">Classic mixture</option>
<option value="earing">Gold Earing</option>
</select>
<INPUT TYPE="button" VALUE="Go" id="go">
</INPUT>
</form>
<HR size="4" color="red" id="hr" />
<!-- <div id="holder"> </div> -->
</div>
You need to use an image tag instead of a div. You could also load images with CSS but thats probably not what you want.
starting on this line:
var holder = document.getElementById("holder");
var image = new Image(128, 128);
if (document.getElementById('selectBox').value == "womens") {
image.src = images[0];
holder.appendChild(image);
holder.appendChild(document.createTextNode(" Women's coat"));
} else if (document.getElementById('selectBox').value == "mens") {
image.src = images[1];
holder.appendChild(image);
holder.appendChild(document.createTextNode(" Men's coat"));
}
Let me elaborate.
In the JavaScript code you are creating a div element here
newdiv = document.createElement('div'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv);
and then you are searching for element with Id holder and setting new image url.
var holder = document.getElementById("holder");
// holder is <div></div> element
if (document.getElementById('selectBox').value == "womens") {
holder.src = images[0] + " Women's coat";
} else if (document.getElementById('selectBox').value == "mens") {
holder.src = images[1] + " Men's coat";
}
holder is a div tag now. it has no src attribute
But div element do not have attribute with name src. so the above code will just add one more attribute to your div tag. but browser will not interpret it.
So if you want load image by setting src attribute, then you probably have to create holder as img tag which has attribute src. like this.
newdiv = document.createElement('img'); //create a img
newdiv.id = 'holder';
mainDiv.appendChild(newdiv);
holder is a img tag. now it has src attribute
now it will work with no problem.

I am working on stack any 3 pictures. When I click one of them, the one I click should be displayed on the top.

I am working on stack any 3 pictures. When I click one of them, the one I click should be displayed on the top.
I want you to help me in my code. I have already mention in title. Here I am attaching the body, style and java Script. every ting is fine but still i am unable to work this.
<!Doctype>
<html>
<head>
<style>
div {
width:420px;
height:300px;
}
div.box1 {
background:#dad7d7;
position:relative;
z-index:1;
}
div.box2 {
background:#ffe7bc;
position:relative;
top:-200px;
left:50px;
z-index:2;
}
div.box3 {
background:#fc9458;
position:relative;
top:-360px;
left:100px;
z-index:2;
}
</style>
</head>
<body>
<div class="box1"> <img class = "imagel" id = "imagel" height = "300" width = "420" src = "images/image1.png"
alt = "(Image1)" onclick = "toTop('image1')" /> </div>
<div class="box2"> <img class = "image2" id = "image2" height = "300" width = "420" src = "images/image2.png"
alt = "(Image2)" onclick = "toTop('image2')" /> </div>
<div class="box3"> <img class = "image3" id = "image3" height = "300" width = "420" src = "images/image3.png"
alt = "(Image3)" onclick = "toTop('image3')" /> </div>
</body>
</html>
Here JavaScript
<script>
var topp = "image3";
function toTop(newTop) {
var domTop document.getElementById(topp).style;
var domNew document.getElementByld(newTop).style;
domTop.zIndex = "0";
domNew.zIndex = "10";
topp = newTop;
}
</script>
You seem to be setting the zIndex attribute to the div element with .box class.
I'd suggest you do document.getElementById(topp).parentElement.style or pass the parent class instead.
Also, you forgot your equal signs here
var domTop document.getElementById(topp).style;
var domNew document.getElementByld(newTop).style;
which should be
var domTop = document.getElementById(topp).style;
var domNew = document.getElementByld(newTop).style;

How can I change the x position of a div via javascript when I click on another div this way?

<body>
<div id = "SiteContainer">
<div id = "NavigationButtons"></div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition();">x</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition();">y</div>
<div id = "VideoWrapper">
<div id = "SlideShowItem">
<img src="Images/A.png" alt="A"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/B.png" alt="B"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/C.png" alt="C" ></img>
</div>
</div>
</div>
</div>
<script>
var wrapper = document.querySelector("#VideoWrapper");
function setPosition(e)
{
if(e.target.name = "forward")
{
if!(wrapper.style.left = "-200%")
{
wrapper.style.left = wrapper.style.left - 100%;
}
}
else
{
if(e.target.name = "back")
{
if!(wrapper.style.left = "0%")
{
wrapper.style.left = wrapper.style.left + 100%;
}
}
}
}
</script>
</body>
Hi, I am very new to javascript. What I am trying to do, is change the x-position of a div when another div (NavigationForward or NavigationBackward) is clicked. However it does not appear to do anything at all. Basically if the div with name forward is clicked, I want to translate the VideoWrapper -100% from it's current position and +100% when "back". The css div itself VideoWrapper has a width of 300%. Inside this div as you can see is a SlideShowItem which is what will change. Perhaps I am adding and subtracting 100% the wrong way?
EDIT:
Thanks everyone for helping me out with this...I had just one more query, I am trying to hide the arrows based on whether the wrapper is at the first slide or the last slide. If its on the first slide, then I'd hide the left arrow div and if it's on the last, I'd hide the right arrow, otherwise display both of em. Ive tried several ways to achieve this, but none of em work, so Ive resorted to using copies of variables from the function that works. Even then it does not work. It appears that my if and else if statements always evaluate to false, so perhaps I am not retrieving the position properly?
function HideArrows()
{
var wrapper2 = document.getElementById("VideoWrapper");
var offset_x2 = wrapper2.style.left;
if(parseInt(offset_x2,10) == max_x)
{
document.getElementById("NavigationForward").display = 'none';
}
else if(parseInt(offset_x2,10) == min_x)
{
document.getElementById("NavigationBackward").display = 'none';
}
else
{
document.getElementById("NavigationForward").display = 'inline-block';
document.getElementById("NavigationBackward").display = 'inline-block';
}
}
//html is the same except that I added a mouseover = "HideArrows();"
<div id = "ShowReelContainer" onmouseover="HideArrows();">
To achieve this type o slider functionality your div VideoWrapper must have overflow:hidden style, and your SlideShowItemdivs must have a position:relative style.
Then to move the slides forward or backward you can use the style left which allows you to move the divs SlideShowItem relative to it's parent VideoWrapper.
I've tested this here on JSFiddle.
It seems to work as you described in your question, although you may need to do some adjustments, like defining the width of your slides, how many they are and so on.
For the sake of simplicity, I defined them as "constants" on the top of the code, but I think you can work from that point on.
CSS
#VideoWrapper{
position:relative; height:100px; white-space:nowrap;width:500px;
margin-left:0px; border:1px solid #000; overflow:hidden; }
.SlideShowItem{
width:500px; height:100px;display:inline-block;position:relative; }
#NavigationForward, #NavigationBackward{
cursor:pointer;float:left; background-color:silver;margin-right:5px;
margin-bottom:10px; text-align:center; padding:10px; }
HTML
<div id = "SiteContainer">
<div id = "NavigationButtons">
</div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition('back');">prev</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition('forward');">next</div>
<div style="clear:both;"></div>
<div id = "VideoWrapper">
<div class= "SlideShowItem" style="background-color:blue;">
Slide 1
</div>
<div class = "SlideShowItem" style="background-color:yellow;">
Slide 2
</div>
<div class = "SlideShowItem" style="background-color:pink;">
Slide 3
</div>
</div>
</div>
</div>
JavaScript
var unit = 'px'; var margin = 4; var itemSize = 500 + margin; var itemCount = 3; var min_x = 0; var max_x = -(itemCount-1) * itemSize;
function setPosition(e) {
var wrapper = document.getElementById("VideoWrapper");
var slides = wrapper.getElementsByTagName('div');
var offset_x = slides[0].style.left.replace(unit, '');
var curr_x = parseInt(offset_x.length == 0 ? 0 : offset_x);
if(e == "forward")
{
if(curr_x <= max_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + -itemSize) + unit;
}
else if(e == "back")
{
if(curr_x >= min_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + itemSize) + unit;
} }
After you analyze and test the code, I don't really know what's your purpose with this, I mean, you maybe just playing around or trying to develop something for a personal project, but if you are looking for something more professional avoid to create things like sliders on your own, as there are tons of plugins like this available and well tested out there on the web.
Consider using jQuery with NivoSlider, it works like a charm and is cross browser.
I would recommend using jQuery, this will reduce your coding by quite a bit. Can read more here: http://api.jquery.com/animate/
I've created a simple fiddle for you to take a look at. This example uses the .animate() method to reposition two div elements based on the CSS 'left' property.
CSS:
#container {
position: absolute;
left: 1em;
top: 1em;
right: 1em;
bottom: 1em;
overflow: hidden;
}
#one, #two {
position: absolute;
color: white;
}
#one {
background: pink;
width: 100%;
top:0;
bottom:0;
}
#two {
background: blue;
width: 100%;
left: 100%;
top:0;
bottom:0;
}
HTML:
<div id="container">
<div id="one">Div One</div>
<div id="two">Div Two</div>
</div>
JavaScript/jQuery:
var one, two, container;
function animateSlides(){
one.animate({
left : '-100%'
}, 1000, function(){
one.animate({
left : 0
}, 1000);
});
two.animate({
left : 0
}, 1000, function(){
two.animate({
left:'100%'
}, 1000);
});
};
$(function(){
one = $('#one');
two = $('#two');
container = $('#container');
setInterval(animateSlides, 2000);
});
JSFiddle Example: http://jsfiddle.net/adamfullen/vSSK8/3/

Show images one after one after some interval of time

I am new person in Front End Development and i am facing one major problem is that i have 3 images placed on each others and now i want to move one image so the other image comes up and then it goes and third image comes up after some interval of time.
I want three images on same position in my site but only wants to see these three images one after one after some interval of time.
Please help how i can do this??
May i use marquee property or javascript???
Non-jQuery Option
If you don't want to go down the jquery route, you can try http://www.menucool.com/javascript-image-slider. The setup is just as easy, you just have to make sure that your images are in a div with id of slider and that div has the same dimensions as one of your images.
jQuery Option
The jQuery cycle plugin will help you achieve this. It requires jquery to work but it doesn't need much setting up to create a simple sliple slideshow.
Have a look at the 'super basic' demo:
$(document).ready(function() {
$('.slideshow').cycle({
fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
});
});
It has many options if you want something a bit fancier.
Here you go PURE JavaScript solution:
EDIT I have added image rotation... Check out live example (link below)
<script>
var current = 0;
var rotator_obj = null;
var images_array = new Array();
images_array[0] = "rotator_1";
images_array[1] = "rotator_2";
images_array[2] = "rotator_3";
var rotate_them = setInterval(function(){rotating()},4000);
function rotating(){
rotator_obj = document.getElementById(images_array[current]);
if(current != 0) {
var rotator_obj_pass = document.getElementById(images_array[current-1]);
rotator_obj_pass.style.left = "-320px";
}
else {
rotator_obj.style.left = "-320px";
}
var slideit = setInterval(function(){change_position(rotator_obj)},30);
current++;
if (current == images_array.length+1) {
var rotator_obj_passed = document.getElementById(images_array[current-2]);
rotator_obj_passed.style.left = "-320px";
current = 0;
rotating();
}
}
function change_position(rotator_obj, type) {
var intleft = parseInt(rotator_obj.style.left);
if (intleft != 0) {
rotator_obj.style.left = intleft + 32 + "px";
}
else if (intleft == 0) {
clearInterval(slideit);
}
}
</script>
<style>
#rotate_outer {
position: absolute;
top: 50%;
left: 50%;
width: 320px;
height: 240px;
margin-top: -120px;
margin-left: -160px;
overflow: hidden;
}
#rotate_outer img {
position: absolute;
top: 0px;
left: 0px;
}
</style>
<html>
<head>
</head>
<body onload="rotating();">
<div id="rotate_outer">
<img src="0.jpg" id="rotator_1" style="left: -320px;" />
<img src="1.jpg" id="rotator_2" style="left: -320px;" />
<img src="2.jpg" id="rotator_3" style="left: -320px;" />
</div>
</body>
</html>
And a working example:
http://simplestudio.rs/yard/rotate/rotate.html
If you aim for good transition and effect, I suggest an image slider called "jqFancyTransitions"
<html>
<head>
<script type="text/javascript">
window.onload = function(){
window.displayImgCount = 0;
function cycleImage(){
if (displayImgCount !== 0) {
document.getElementById("img" + displayImgCount).style.display = "none";
}
displayImgCount = displayImgCount === 3 ? 1 : displayImgCount + 1;
document.getElementById("img" + displayImgCount).style.display = "block";
setTimeout(cycleImage, 1000);
}
cycleImage();
}
</script>
</head>
<body>
<img id="img1" src="./img1.png" style="display: none">
<img id="img2" src="./img2.png" style="display: none">
<img id="img3" src="./img3.png" style="display: none">
</body>
</html>​
Fiddle: http://jsfiddle.net/SReject/F7haV/
arrayImageSource= ["Image1","Image2","Image3"];
setInterval(cycle, 2000);
var count = 0;
function cycle()
{
image.src = arrayImageSource[count]
count = (count === 2) ? 0 : count + 1;
}​
Maybe something like this?

Categories

Resources