Javascript: Displaying Image According To Select Box Value
In my program I have created select box and button. upon selecting different value from select box image should be displayed as shown in expected output. There are two buttons prev
Solution 1:
There are a few tiny errors all adding up to this not working, I'll try to remember and point them out. Here is a working example with only 2 images -you can fill yours back in
- you have a div for your image "holder" this should be an
<img />
tag var imgLen = imageObj.length;
should bevar imgLen = images.length;
use the length of your array not the obj.preBtn.addEventListener
should bebtnPre.
preBtn
doesn't existholder.src = images[0] + "<br>" + " Women's coat";
the src attribute needs to be a valid url and you mess that up when you append<br>
and a string to it.imageObj.src=images[i];
needs to reference your "holder" notimageObj
so it should bedocument.getElementById("holder").src = images[i];
- You don't need to dynamically put the next and previous buttons each image load (you aren't even clearing them) so the DOM keeps piling up with buttons.
- You should use numbers as values so you can set the select to the correct description on next and prev
- you need to keep track of i when the user jumps on the select (set i on the select change)
// counter
var i = 0;
// create object
imageObj = new Image(128, 128);
// set image list
images = new Array();
images[0] = "https://cdn-image.myrecipes.com/sites/default/files/summer-sweet-lemonade-cl.jpg";
images[1] = "http://www.greatamericancookies.com/app/themes/greatamericancookies/library/images/home/carousel3.png";
images[2] = "final_images/ktoys.jpg";
images[3] = "final_images/mixture.jpeg";
images[4] = "final_images/earing.jpg";
var imgLen = images.length;
var go = document.getElementById('go');
var select = document.getElementById('selectBox');
var desc = document.getElementById('desc');
go.addEventListener("click", loadItem);
function loadItem() {
var holder = document.getElementById("holder");
if (document.getElementById('selectBox').value == 0) {
holder.src = images[0];
desc.innerHTML = document.getElementById("select0").getAttribute("data-desc");
i = 0;
} else if (document.getElementById('selectBox').value == 1) {
holder.src = images[1];
desc.innerHTML = document.getElementById("select1").getAttribute("data-desc");
i = 1;
} else if (document.getElementById('selectBox').value == 2) {
holder.src = images[2];
desc.innerHTML = document.getElementById("select2").getAttribute("data-desc");
i = 2;
} else if (document.getElementById('selectBox').value == 3) {
holder.src = images[3];
desc.innerHTML = document.getElementById("select3").getAttribute("data-desc");
i = 3;
} else if (document.getElementById('selectBox').value == 4) {
holder.src = images[4];
desc.innerHTML = document.getElementById("select4").getAttribute("data-desc");
i = 4;
}
document.getElementById('prev').style.display = "";
document.getElementById('next').style.display = "";
}
function nxt() {
if (i < imgLen - 1) {
i++;
} else {
i = 0;
}
select.value = i;
desc.innerHTML = document.getElementById("select" + i).getAttribute("data-desc");
document.getElementById("holder").src = images[i];
}
function prvs() {
if (i > 0) {
i--;
} else {
i = imgLen - 1;
}
select.value = i;
desc.innerHTML = document.getElementById("select" + i).getAttribute("data-desc");
document.getElementById("holder").src = images[i];
}
body {
background-image: url("final_images/back.jpg");
}
img {
width: 200px;
}
.container {
/*width: 600px;*/
/*height: 200px;*/
border: inset;
background-color: rgba(255, 234, 134, 0.9);
}
#selectBox {
margin-left: 210px;
width: 160px;
}
#below_hr {
width: 600px;
background-color: #ffffff;
}
#preBtn {
margin-left: 170px;
margin-top: 170px;
}
<div class='container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
<option id="select0" data-desc="a womans coat" value=0>Women's coat</option>
<option id="select1" data-desc="a mens winter coat" value=1>Men's coat</option>
<option id="select2" data-desc="a kids toy to play with" value=2>Kid's toys</option>
<option id="select3" data-desc="a classic mixture" value=3>Classic mixture</option>
<option id="select4" data-desc="a beautiful gold earing" value=4>Gold Earing</option>
</select>
<INPUT TYPE="button" VALUE="Go" id="go">
</INPUT>
</form>
<HR size="4" color="red" id="hr">
<img id="holder" /><br/>
<span id="desc"></span><br/><br/>
<button id="prev" onclick="prvs()" style="display:none">Previous</button>
<button id="next" onclick="nxt()" style="display:none">Next</button>
</div>
Solution 2:
You have quite a few errors inside your code, Andrew (+1 for that) already listed them in his answer. But i think you maybe should also try to be more dynamic and create the selection from for example a configuration object.
Here's an example:
// CLASS
var ImageSelector = (function(doc) {
// private variables
var _config,
_selectionEl,
_imageEl,
_prevBtnEl,
_nextBtnEl,
_currentIndex = 0;
// constructor
function ImageSelector(config) {
var imageholderEl = doc.querySelector(config.imageholder);
_config = config;
_selectionEl = doc.querySelector(config.selection);
_prevBtnEl = doc.querySelector(config.prevBtn);
_nextBtnEl = doc.querySelector(config.nextBtn);
if(!_selectionEl || !imageholderEl) {
throw new Error('no selection or imageholder element found');
}
_imageEl = new Image();
imageholderEl.appendChild(_imageEl);
_generateSelection();
_bindEvents();
}
// private methods
function _generateSelection() {
var fragment = doc.createDocumentFragment();
var items = _config.items;
for(var i = 0; i < items.length; ++i) {
var item = items[i];
var option = doc.createElement('option');
option.value = item.value;
option.textContent = item.name;
fragment.appendChild(option);
}
_selectionEl.appendChild(fragment);
_selectionEl.selectedIndex = _currentIndex;
}
function _loadImage() {
var items = _config.items;
var item = items.find(itm => itm.value === _selectionEl.value);
_imageEl.src = item.image;
_prevBtnEl.style.display = null;
_nextBtnEl.style.display = null;
}
function _bindEvents() {
var goBtnEl = doc.querySelector(config.goBtn);
_selectionEl.addEventListener('change', _loadImage);
if(_prevBtnEl) {
_prevBtnEl.addEventListener('click', ImageSelector.prototype.prev);
_prevBtnEl.style.display = 'none';
}
if(_nextBtnEl) {
_nextBtnEl.addEventListener('click', ImageSelector.prototype.next);
_nextBtnEl.style.display = 'none';
}
goBtnEl && goBtnEl.addEventListener('click', _loadImage)
}
function _changeIndex(direction) {
var length = _config.items.length;
_currentIndex = (_currentIndex + direction) % length;
if(_currentIndex < 0) _currentIndex = length -1;
_selectionEl.selectedIndex = _currentIndex;
_selectionEl.dispatchEvent(new Event('change'));
}
// public methods
ImageSelector.prototype.next = function() {
_changeIndex(1);
}
ImageSelector.prototype.prev = function() {
_changeIndex(-1);
}
return ImageSelector;
})(document);
// CONFIGURATION
var config = {
selection: '#selectBox',
imageholder: '#holder',
goBtn: '#go',
prevBtn: '#prev',
nextBtn: '#next',
items: [
{ name: "Women's coat", value: "womens", image: "https://thumb7.shutterstock.com/display_pic_with_logo/562036/116906134/stock-photo-portrait-of-brown-eyed-cat-isolated-on-white-background-116906134.jpg" },
{ name: "Men's coat", value: "mens", image: "https://thumb1.shutterstock.com/display_pic_with_logo/154447/235089946/stock-photo-cute-little-red-kitten-sleeps-on-fur-white-blanket-235089946.jpg" },
{ name: "Kid's toys", value: "kids", image: "https://thumb9.shutterstock.com/display_pic_with_logo/2288597/574871668/stock-photo-brown-cat-playing-relaxed-on-the-mobile-574871668.jpg" },
{ name: "Classic mixture", value: "mixture", image: "https://thumb9.shutterstock.com/display_pic_with_logo/4363153/520870675/stock-photo-lovely-cat-in-human-hands-vintage-effect-love-for-the-animals-520870675.jpg" },
{ name: "Gold Earing", value: "earing", image: "https://thumb9.shutterstock.com/display_pic_with_logo/428239/454556905/stock-photo-happy-scottish-kitten-looking-at-camera-isolated-on-white-background-454556905.jpg" }
]
}
// INITIALISATION
var selector = new ImageSelector(config);
body {
background-image: url("final_images/back.jpg");
}
img {
width: 200px;
}
.container {
/*width: 600px;*/
/*height: 200px;*/
border: inset;
background-color: rgba(255, 234, 134, 0.9);
}
#selectBox {
margin-left: 210px;
width: 160px;
}
#below_hr {
width: 600px;
background-color: #ffffff;
}
#preBtn {
margin-left: 170px;
margin-top: 170px;
}
<div class='container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
</select>
<input type="button" value="Go" id="go" />
</form>
<hr size="4" color="red" id="hr" />
<div id="holder"></div>
<button id="prev">Previous</button>
<button id="next">Next</button>
</div>
Post a Comment for "Javascript: Displaying Image According To Select Box Value"