I want to see if this is possible, i need to change a select element content to be displayed as divs using images just like a color picker. when the user selects clicks on a colored div i want an image to be displayed on the page. Also would i still be able to capture the selected item in a form hidden field?
It's a shirt building page, i have 12 colours, and 4 parts to a shirt. Any help, guidance would be appreciated.
My current code is below pretty basic.
function swapImage(){
var image = document.getElementById("neck");
var dropd = document.getElementById("imageneck");
image.src = dropd.value;
};
<select name="imageneck" id="imageneck" onChange="swapImage()">
<option value="WHITE-4.png">White</option>
</select>
<div id="poloneck"><img id="neck" src="WHITE-4.png" /></div>
A demo of the page image based is here ..demo
Thanks
I suggest you creating a <div> or <table> box for every picker. [Working demo]
Javascript
// instead of swapImage
function setImage(subject, color) {
var image = document.getElementById(subject);
image.src = color + ".jpg"; // e.g.: white.jpg
}
// general click event handler for changing color
function pickerClick(e) {
// event -> which box -> which color
e = e || event;
var target = e.target || e.srcElement;
if ( target.nodeName.toUpperCase() != "TD" ) return;
var color = target.className;
var picker = target.parentNode.parentNode;
// change <input> field
document.getElementById("imageneck").value = color;
// change appearance
setImage(picker, color);
}
// a specific click handler for neck
var collarbox = document.getElementById('collar');
collarbox.onclick = pickerClick;
HTML
<table class="picker" id="collar">
<tr>
<td class="white"></td>
<td class="black"></td>
<td class="red"></td>
<td class="blue"></td>
</tr>
</table>
CSS
.white { background: white }
.black { background: black; }
.red { background: red; }
.blue { background: blue; }
.picker { border: 1px solid #ccc; }
.picker td { width:30px; height: 30px; cursor: pointer; }
http://api.jquery.com/val/
Check the demo for select box.
You can change your color or image based on select box selected value.
You can use jquery add function for adding css or
addClass function and removeClass for changing class
Related
I am trying to set the background color of a div upon page load to blue. Then I want to cycle through 3 different colors (red, yellow, and green) when clicked and have the selected color remain. Below is my sample code. You can see the first two do nothing when clicked due to setting the blue color on load. I didn't load the 3rd div to blue on load to show how I want the behavior to act once clicked. Any help is appreciated.
function colorload() {
var element = document.getElementById("day1");
element.style.backgroundColor = "blue";
var element = document.getElementById("day2");
element.style.backgroundColor = "blue";
}
function changeColor(e, numb) {
var color = e.className;
e.className = (color == 'red') ? 'amber' :
(color == 'amber') ? 'green' :
(color == 'green') ? 'red' :
'undefined';
}
<style onload="colorload()">
.red {background-color:red;}
.amber {background-color:yellow;}
.green {background-color:green;}
div {
width:200px;
height:100px;
margin:50px;
text-align: center;
vertical-align: middle;
line-height: 90px;
font-weight:bold;
user-select: none;
cursor:pointer;
}
</style>
<html>
<body>
<div class="red" id="day1" onclick="changeColor(this, 1)">One</div>
<div class="green" id="day2" onclick="changeColor(this, 2)">Two</div>
<div class="amber" id="day3" onclick="changeColor(this, 3)">Three</div>
</body>
</html>
i made an update to your html and JS codes,
i used in this example .style instead of css classes, if you are interested on using classes you can refer to my comments and this link on mdn it's pretty simple.
Html file
<html>
<body>
<!-- i used .btn class and data-col to play with indexes -->
<div class="btn" id="day1" data-col="0" onclick="changeColor(event)">One</div>
<div class="btn" id="day2" data-col="0" onclick="changeColor(event)">Two</div>
<div class="btn" id="day3" data-col="0" onclick="changeColor(event)">Three</div>
</body>
</html>
Js file
let divs;
let colors = ['blue', 'red', 'green' , 'yellow'];
// when loading the page, we are catching all divs having the class "btn"
// to render it with Blue background
document.body.onload = function() {
divs = document.querySelectorAll('.btn');
divs.forEach(btn => {
const selectedColorIndex = btn.dataset.col;
btn.style = 'background:'+colors[selectedColorIndex];
});
};
function changeColor(e) {
// catch the clicked div which passed by the "event" value in the html file
let divElement = e.target;
// get data-col value and convert it to number with (+)
const selectedColorIndex = +divElement.dataset.col;
// check if we have a next color or get the red index
const nextSelectedColor = selectedColorIndex +1 >= colors.length?1:selectedColorIndex+1;
// update data-col with the next new color index to conserve the iteration (loop)
divElement.dataset.col = nextSelectedColor;
// if you want to use classes you can access with
// .classList.add(..) and .classList.remove(..) OR
// .classList.toggle(..)
divElement.style = 'background:'+ colors[nextSelectedColor]; // update the element background with selected color
}
You can also replay the same codes or update: it here is the full replayed code in JSFiddle which i made to make it more easy.
I have an image that I'm trying to change the color of, I have a <ul> of colors, all displayed in small squares. I want to modify the color of my image based on which box the user clicks.
<li swatch="3FB8AF"></li>
<li swatch="7FC7AF"></li>
<li swatch="DAD8A7"></li>
<li swatch="FF9E9D"></li>
<li swatch="FF3D7F"></li>
Ex. If someone clicks, <li swatch="7BE0D0"></li>, the image should change to that color.
I can't understand what you mean by color if image. Here is example of changing color div
<html>
<head>
</head>
<body>
<ul id="colors">
<li swatch="#3FB8AF"></li>
<li swatch="#7FC7AF"></li>
<li swatch="#DAD8A7"></li>
<li swatch="#FF9E9D"></li>
<li swatch="#FF3D7F"></li>
</ul>
<div style="height:500px;width:500px;font-size:50px" id="mainElm">Elment whose color will change</div>
<script>
var colors = document.querySelectorAll('ul#colors > li');
for(let color of colors){
color.style.backgroundColor = color.getAttribute("swatch");
color.style.height = "50px";
color.style.width = "50px";
color.onclick = function(){
document.getElementById('mainElm').style.backgroundColor = color.getAttribute('swatch');
}
}
</script>
</body>
</html>
It's not clear what you mean by modifying the colour of an image. However here's an example that adds background colour to each swatch square, a click listener to their container, and a function that adds color to another element when a swatch square is clicked. It will give you some idea about the steps needed when you come to code this yourself.
1) You should use data attributes in your HTML. data-color="3FB8AF" instead of swatch="3FB8AF" to ensure your HTML is valid.
2) I'm using "event delegation". Instead of adding a listener to each color element you can add one listener to the containing element which captures the events as they bubble up the DOM from its children.
Hope this helps.
// Cache the swatch element (the `ul`), and add
// an event listener to it. This calls `handleClick`
// when it is clicked or any of its child elements are clicked
const swatch = document.querySelector('ul');
swatch.addEventListener('click', handleClick, false);
// Cache the color squares in the swatch, and the "image" element
const colorSquares = document.querySelectorAll('li');
const img = document.querySelector('.image');
// Destructures the dataset from the element that
// was clicked and calls `setColor`, passing in the
// element to which we need to apply the color
function handleClick(e) {
const { dataset: { color } } = e.target;
setColor(img, color);
}
// Accepts an element and a color - sets
// the background color of the element.
// Note: because the data-color attribute doesn't
// contain a preceding hash we have to add it here
function setColor(el, color) {
el.style.backgroundColor = `#${color}`;
}
// Iterates over the color squares and set each
// of their background color to the hex color in the
// dataset
[...colorSquares].forEach(colorSquare => {
const { dataset: { color } } = colorSquare;
setColor(colorSquare, color);
});
ul { padding-left: 0; display: flex; flex-direction: row; list-style-type: none; }
li { height: 20px; width: 20px; }
li:hover { cursor: pointer; }
.image { text-align: center; border: 1px solid #676767; height: 50px; width: 100px; }
<ul>
<li data-color="3FB8AF"></li>
<li data-color="7FC7AF"></li>
<li data-color="DAD8A7"></li>
<li data-color="FF9E9D"></li>
<li data-color="FF3D7F"></li>
</ul>
<div class="image">IMAGE</div>
I have 12 tiles (100px by 100px squares) on my screen.
Each tile by default is set to display:block and has a white background background: rgb(255,255,255);
If a tile is clicked, the background becomes orange rgb(255,161,53). Using the following function:
function changeColour(id){
{
var current_bg = document.getElementById(id).style.backgroundColor;
if(current_bg != "rgb(255, 161, 53)"){
document.getElementById(id).style.backgroundColor = "rgb(255,161,53)";
} else if(current_bg == "rgb(255, 161, 53)"){
document.getElementById(id).style.backgroundColor = "rgb(255,255,255)";
}
}
At the bottom of the page I have a button called "showHide", once it is pressed I want only the tiles with an orange background to be shown. Once it pressed again I want ALL of the tiles to appear.
What I meant with meta data
A break down:
The first block iterates over every tile and sets an onclick handler
When you click a block it will either set orange to the class list or remove it using toggle. The actual orange coloring comes from the stylesheet. Where tiles that don't have orange in their class names :not() get a white background.
When you click the show hide button you'll see the same trick. Every class list that doesn't contain orange get hidden by the hide class name that gets toggled.
I've used a different approach here, using class names as selectors and play with them to get the desired result.
function changeColour() {
this.classList.toggle("orange");
//if hiding is on we need to also hide that block
if (this.parentElement.querySelectorAll("div.tiles.hide").length > 0)
{
this.classList.add("hide");
}
}
var divs = document.querySelectorAll("div.tiles");
//use Array.prototype.forEach to iterate over nodelist
Array.prototype.forEach.call(divs, function(element){
element.addEventListener("click", changeColour);
});
document.querySelector("button.hide").addEventListener("click", showHide);
function showHide(){
Array.prototype.forEach.call(divs, function(element){
if (!element.classList.contains("orange"))
{
element.classList.toggle("hide");
}
});
}
div.tiles {
display: inline-block;
width: 100px;
height: 100px;
border: 1px solid grey;
}
div.tiles:not(.orange) {
background-color: #ffffff;
}
div.tiles.orange {
background-color: rgb(255,161,53);
}
div.tiles.hide {
display: none;
}
<div class="tiles"></div>
<div class="tiles"></div>
<div class="tiles"></div>
<div class="tiles"></div>
<div class="tiles"></div>
<button class="hide">show/hide white tiles</button>
So I made a 5x5 grid using HTML's <table> element. I want each cell to turn red when it is clicked and revert back to white when it isn't. It looks like it won't detect the first ever click on each cell. Once the first click has been triggered, it alternates from red and white normally under 1 click, but when you click it for the very first time for that instance, it does not respond. Why is it that a cell responds on the first click after it has been clicked on twice, but doesn't respond on the first click if it has never been touched before?
HTML snippet:
<div class="board">
<table type="board">
<tr>
<td id="r1-c1" onclick="changeColor('r1-c1')"></td>
<td id="r1-c2" onclick="changeColor('r1-c2')"></td>
<td id="r1-c3" onclick="changeColor('r1-c3')"></td>
<td id="r1-c4" onclick="changeColor('r1-c4')"></td>
<td id="r1-c5" onclick="changeColor('r1-c5')"></td>
</tr>
...
</table>
</div>
<button id="submit" onclick="submitted()">Generate</button>
The snippet is nested inside body and 2 div tags respectively.
CSS snippet:
table[type=board],tr,td{
background-color: white;
min-width: 80px;
min-height: 380px;
border: 2px solid black;
text-align: center;
font-size: 25px;
margin: 0px;
}
JS code:
function changeColor(id)
{
if(document.getElementById(id).style.backgroundColor == "white"){
document.getElementById(id).style.backgroundColor = "red";
}else{
document.getElementById(id).style.backgroundColor = "white";
}
}
Use the following code. It will work.
function changeColor(id){
if( (document.getElementById(id).style.backgroundColor == "white") || (document.getElementById(id).style.backgroundColor == "")){
document.getElementById(id).style.backgroundColor = "red";
}else{
document.getElementById(id).style.backgroundColor = "white";
}
}
You have not provided the HTML, So I have to create the DOM.
document.getElementById(id).style.backgroundColor
Do you mean to say each of the cell has an id?
Which may be too complex for large grid. Instead you should use rowIndex & cellIndex to locate a particular cell.
Also you can use event object and find the target. Saying that it mean event.target will help you to locate the cell which is clicked
var getTable = document.getElementById("demoTable");
//Declare a variable to hold the cellIndex & rowIndex
// On next click check if this values,& if not null change the background color of that cell
var col = "";
var row = "";
getTable.addEventListener('click',function(event){
console.log(col,row)
if(col !== "" && row !== "" ){
document.getElementById('demoTable').rows[row].cells[col].style.backgroundColor ="transparent" ;
}
col = event.target.cellIndex;
row = event.target.parentNode.rowIndex;
//Set background of the cell on which it is clicked
document.getElementById('demoTable').rows[row].cells[col].style.backgroundColor ="red" ;
})
JSFIDDLE
Right now i am changing the image by dropdown selection. But i want to change image by click on choice of image Like.
If the user click on green t-shirt image then set green image in <div>, If user click on yellow t-shirt then set yellow t-shirt in <div>.
But right now i am using dropdown for this procedure.
var bgArray = [
'https://d3s16h6oq3j5fb.cloudfront.net/1.13.0/img/new-city-home/bang-img/softtoys3.jpg',
'https://d2z4fd79oscvvx.cloudfront.net/0020715_be_my_valentine_chocolate_box_205.jpeg'
]
$('#imageroom').on('change', function() {
value = $(this).val() - 1;
$('#backgroundIMage').css({
'background-image': 'url(' + bgArray[value] + ')'
});
});
#backgroundIMage {
width: 400px;
height: 300px;
outline: 1px dotted gray;
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label>Change image</label>
<select size="1" id="imageroom">
<option value="1">Image 1</option>
<option value="2">IMage 2</option>
</select>
<!-- for demo only -->
<hr>
<div id="backgroundIMage"></div>
You can handle the click event on an image. In the example below, I loop through the bgArray and dynamically display all the images in that array.
When one of the images is clicked, I show that image in the backgroundIMage element. Notice that I am using event delegation to make sure the image click works for any images that are dynamically added to the picker.
var bgArray = [
'https://d3s16h6oq3j5fb.cloudfront.net/1.13.0/img/new-city-home/bang-img/softtoys3.jpg',
'https://d2z4fd79oscvvx.cloudfront.net/0020715_be_my_valentine_chocolate_box_205.jpeg'
];
$("#picker").on("click", "img", function() {
//use event delegation to handle click event of any img tags in #picker
$('#backgroundIMage').css({
'background-image': 'url(' + this.src + ')'
});
//toggle selected
$("#picker img").removeClass("selected");
$(this).addClass("selected");
});
$(function() {
//initialize the picker on document load
bgArray.forEach(function(src) {
var img = new Image(50, 50);
img.src = src;
$("#picker").append(img);
});
//default the first one to be selected
$("#picker img").first().trigger("click");
});
#backgroundIMage {
width: 400px;
height: 300px;
outline: 1px dotted gray;
margin: 0 auto;
}
#picker img {
padding: 5px;
}
.selected {
background-color: dodgerblue;
border-radius: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Change image
<div id="picker"></div>
<hr>
<div id="backgroundIMage"></div>
Although it is king of hard to know exactly what you are trying to do, you should try to work with the click event of the image.
For a specific image :
$('#myImageId').click(function(){
$(this).css//etc..
});
For all images :
$('img').click(function(){
$(this).css//etc..
});