how to create dynamic squares with HTML and CSS - javascript

My goal is to create 3 inputs where you can choose the color of the cube, the size and the amount of cubes. The picture down below is my classmates final work but he wouldn't give me the code. We were given a template to start on and this is what I have so far.
<style>
.square {
height: 50px;
width: 50px;
background-color: var(color1);
}
</style>
<script>
function makeSquare(size, color){
var div = document.createElement("div");
div.style.display = "inline-block";
div.style.height = size+"px";
div.style.width = size+"px";
div.style.backgroundColor=color;
div.style.margin="5px";
document.body.appendChild(div);
}
function addSquares(){
if (inputColor == "blue")
var color1 = '#555';
}
</script>
</head>
<body>
<p>Number of squares:<input type="text" id="inputNumber"></p>
<p>Color of squares:<input type="text" id="inputColor"></p>
<p>Size of squares:<input type="text" id="inputSize"></p>
<button onclick=addSquares()>Add squares</button>
<div class="square"></div>
</body>
</html>
as you can maybe guess, this does not work and I have no clue how to do this...
I hope you can help me

For example have a look at jQuery css() method. There you can add or remove css styling from an element. I will not post a solution for you because this is clearly your homework but research around this topic and you can handle this task easily.

I am showing you a way to correct your code,
I can't see where you have called makeSquare().
In addSquares(), did you get value of inputColor?
you need to get value of each input and pass SIZE, COLOR(if its not fetched and set earlier stage) and NUMBER in makeSquare()
Need to loop NUMBER's time to get block in body. inside that create you square block with COLOR and SIZE.

Related

How to set order to arrays when I click next and previous on JavaScript?

I want to create a image viewer where you click next and previous to change the image.
So far the buttons next and previous changes the image. However when I click next then previous, the image doesn't go to the previous image instead it goes to the starting image.
My guess is to create a variable var = newImage and use that variable on function change2() and create a new varirable var= newImage2 and use that on function change().
is that possible?
<!DOCTYPE html>
<html>
<head>
<title>JS ChangeImage</title>
</head>
<body>
<h1 align="center">Change Image</h1>
<br>
<div class= "container" align="center">
<button onclick="change2()">Previous</button>
<img src="html5.png" style="height: 500px; width: 500px" id="changeimg">
<button onclick="change()">Next</button>
</div>
</body>
<script>
var img=0;
var imgArr = ["html5.png","css3.png","javascript.png"]
function change() {
var image = document.getElementById('changeimg');
console.log("current image =>", imgArr[img])
document.getElementById('changeimg').src =imgArr[img];
if (img== 2) img = 0;
else
img++;
}
function change2() {
var c1=
document.getElementById('changeimg').src =imgArr[img];
console.log("current image =>", imgArr[img])
if (img== 0) img = 2;
else
img--;
}
First, I noticed that you are changing the img variable after assigning the image to the element. I think you should switch the order. The way it is now, when you click Next, the number advances, but the picture is associated with the previous number. If you then click Previous, the number will reduce, but the image will appear to advance.
I've made some other changes for simplicity here:
HTML:
<h1 align="center">Change Image</h1>
<br>
<div class= "container" align="center">
<button onclick="change(event)" name='1'>Previous</button>
<img src="html5.png" style="width: 500px" id="changeimg">
<button onclick="change(event)" name='2'>Next</button>
</div>
JS:
var currentImg = 0;
const imgArr = ["html5.png","css3.png","javascript.png"]
const change=(event)=>{
if(event.target.name==='1'){
currentImg>0?currentImg--:currentImg=2;
} else if(event.target.name==='2'){
currentImg<imgArr.length-1?currentImg++:currentImg=0;
}
console.log(currentImg);
document.getElementById('changeimg').src = imgArr[currentImg];
}
Please note the use of the 'name' attribute of the for use in the logic of the change function. This allows me to use only one function for both buttons. I hope this helps.

How to change the colour of a div element when clicked?

I have a this html page, Whenever the element with class name FreeSeat is clicked I want to change the colour of that div element.Below is my html page
<html>
<head>
<title>
QuickBus
</title>
<link type="text/css" rel="stylesheet" href="Seat.css">
</head>
<body>
<div id="Bus">
<div class="Row">
<div class="FreeSeat" ></div>
<div class="FreeSeat" ></div>
<div class="ResSeat" ></div>
<div class="ResSeat" ></div>
<div class="ResSeat" ></div>
</div>
</div>
<body>
</html>
It will be very helpful if anyone can help me out with this .
Considering that you want to use pure JS and not any library, you'd have to manually add event listeners to your classes.
And it has been solved for a similar problem here
var freeclass = document.getElementsByClassName("FreeSeat");
var myFunction_Free = function() {
this.style.color = "blue";
}
for(var i=0;i<freeclass.length;i++){
freeclass[i].addEventListener('click', myFunction_Free, false);
}
But for your case, here's a working fiddle
JQuery is amazing for these sorts of things.
Say you have a div with id 'box1'
<div id='box1'></div>
Style it with css
#box1 {
width:100px;
height:100px;
background-color:white;
border:1px solid black;
}
Using JQuery, you can make this call:
$( "#box1" ).click(function() {
$('#box1').css('background-color', 'red');
});
And now whenever your div is clicked, the colour will change, you can customise this however much you like.
Here is a JSFiddle demo.
Also, since you didn't specify exactly what you want to change the colour of, in my example jquery, it is telling the browser that when a div with an id of box1is clicked, change the background-color of the div with an id of box1, you can change anything though.
If you have a <p> tag you can change that too when the div is clicked, hope this helped!
You can use the following method to change the background color of an element by class:
const free_seat = document.getElementsByClassName('FreeSeat');
free_seat[0].style.backgroundColor = '#ff0';
Each element can be referenced by its index:
free_seat[0] // first div
free_seat[1] // second div
Therefore, we can create a function that will be called whenever the click event is delivered to the target:
const change_color = () => {
this.style.backgroundColor = '#ff0';
};
for (let i = 0; i < free_seat.length; i++) {
free_seat[i].addEventListener('click', change_color);
}
Note: You can also use document.querySelectorAll('.FreeSeat') to obtain a NodeList of elements of a certain class.
You can use simply the css focus pseudo-class for this:
#foo:focus {
background-color:red;
}
<div id="foo" tabindex="1">hello world!</div>
Dont forget to set the tabindex.

How to show a div near a button

I have a page which has a lot of buttons. What I need to do is to show a div near the button. I tried this:
<style>
#noteDiv {display:none; position: absolute; background-color: white; border: 1px solid blue;}
</style>
<script>
function showNote(e) {
var x = 0, y = 0;
if (!e) e = window.event;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else if (e.clientX || e.clientY) {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
document.getElementById("noteDiv").style.display = "block";
document.getElementById("noteDiv").style.left = (x)+"px";
document.getElementById("noteDiv").style.top = (y-350)+"px";
}
function hideNote() {
document.getElementById("noteDiv").style.display = "none";
}
</script>
<body>
<?php
echo "<button type ='button' id = 'noteButton'>Note</button>";
echo "<script>document.getElementById('noteButton').onclick = showNote;\n";
echo "</script>";
?>
</body>
<div id='noteDiv' >
<div ><span onclick="hideNote()">Close</span></div>
<br clear="all">
<div id='noteContent' style='max-height: 30em'></div>
</div>
It does work. But sometimes the page will show one more div on top of the page, like a warning message, and thus the noteDiv's position will be far from the buttons to which it should attach.
My thinking is to get the position of the buttons, and send the x, y values of the button position to the function showNote(), from there show the noteDiv. I don't know if this idea is reasonable and how to get and transfer the current clicked button's position to javascript?
Any suggestions and hints will be appreciated!
From the beginning.
Load javascript on top of your page is a very bad idea. I'll let the tons of web articles to explain you why. Just to say one reason, the js files are downloaded before the html is rendered (depending on the browser), resulting in a slower rendering of the page.
About your approach:
Three words: separation of concerns. Positioning dom elements is not what belongs to javascript (except some very rare occasions).
Styling the DOM, which comprehends positioning of the objects, belongs to the Cascading Style Sheet, also known as CSS.
So if something is not rendered in the right way, don't try to fix it with javascript. It will only drives you to enormous headaches.
For a better answer, please provide a code that can show us the error.
UPDATE
Here is a working example (probably not optimised) of what you are maybe trying to achieve. Please, please, please, please... read a book about html, css and js. It's totally worth it. I didn't use php, didn't need it.
Just for the records, the general structure of an html page I personally use is like this one:
html
head
title
meta
styles link
styles sections
js **LIBRARIES** which need to be loaded on **TOP**
google analytics
body
html content
js **LIBRARIES** which need to be loaded on **BOTTOM**
js scripts
And for your sanity, and of the people who helps you, indent correctly (it's also a sign of respect to the people who are reading your code).
Here is the code with the snippet:
function toggleNote(id) {
var noteParent = document.getElementById(id);
var note = noteParent.querySelector('.note');
var display = "none";
if (note.style.display == "none" || note.style.display == "" ) {
display = "block";
}
note.style.display = display;
}
.note {
display: none;
position: relative;
background-color: white;
border: 1px solid blue;
}
.noteContent {
max-height: 30em
}
<body>
<div class="buttonContainer" id="note0">
<button id='noteButton' onclick="toggleNote('note0')">Note</button>
<div class='note'>
<div>
<button onclick="toggleNote('note0')">Close</button>
</div>
<br clear="all">
<div class='noteContent'>It's something!</div>
</div>
</div>
</body>
All the HTML like <button> <div> <span> <ul><li> <table> etc MUST be inside the <body> </body> tag:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<!-- you can include css and javascript here -->
<!-- but best place to include javascript ist at the bottom -->
<!-- see last comment -->
</head>
<body>
<?php echo '<button type="button" id="noteButton">Note</button>'; ?>
<!-- best place to include javascript or echo them with PHP what ever
right before the closing body tag -->
</body>
</html>
You are echoing a <button> via PHP before the opening <body> tag which is wrong. Try use something like firebug and https://validator.w3.org/

I want to change background of div onclick

How to get clicked image as background of div? I new to javascript. I tried using onclick but the code did not work.I hope may be due to programming mistakes.
<div id="canvas"></div>
<div id="containerA">
<div id="one" ><img src="https://stepupandlive.files.wordpress.com/2014/09/3d-animated-frog-image.jpg" id="image" onclick="change();"/></div>
function change(){
document.getElementById("image").style.backgroundImage = this('src');
};
change your code to this -
<div id="canvas"></div>
<div id="containerA">
<div id="one" ><img src="https://stepupandlive.files.wordpress.com/2014/09/3d-animated-frog-image.jpg" id="image" onclick="change(this);"/></div> // passed this to the parameter
function change(obj){
document.getElementById("canvas").style.backgroundImage = obj.src; // here
};
You declared a function, but you didn't ask it to run. Try this or the code snippet below. Also, you can separate codes in order to control well.
function changeImg() {
document.getElementById("canvas").style.background = "url('//stephboreldesign.com/wp-content/uploads/2012/03/lorem-ipsum-logo.jpg')"
}
document.getElementById("canvas").onclick = changeImg;
#canvas { /* just for test, you can change by yourself */
width: 325px;
height: 325px;
background: red;
}
<div id="canvas"></div>
And here on JSBin is another version if you'd like to change the background between two images, or more. Below are some references for you to know more about function used in example.
W3C School - style change, W3C School - onclick event
MDN - style change, MDN - onclick event
Pass this to the onclick function like this
<div id="canvas"></div>
<div id="containerA">
<div id="one" ><img src="https://stepupandlive.files.wordpress.com/2014/09/3d-animated-frog-image.jpg" id="image" onclick="change(this);"/></div>
</div>
And this is what you do in the Javascript function
function change(img){
var urlString = 'url(' + img.src + ')';
document.getElementById("canvas").style.backgroundImage =urlString;
};
And this should definitely work!
1.you didnt added Jquery
2. On click of image you are calling "change" method but you have to correct the method name.
In below image check the red rectangles for errors-
function changeImage(imgObj){
bgImage = imgObj.src;
$("#updateDiv").css('background-image','url('+bgImage+')');
}
http://plnkr.co/edit/RL7T0a?p=preview
I would suggest to use jQuery in your project. With jQuery something like this could work:
var imageSource = "";
$("#img").click(function(){
imageSource = $(this).attr("src");
$('#canvas').css("background-image", "url("+imageSource+")");
});

Change a background image of a div on click

Okay, I think my head is being dense. But I cant seem to get this to work. I'm doing a website for a photographer, and he wants to be able to let a user change the frame that they would like from a choice of 3. Easiest way I thought to do this was to create a div, and then have it change class based on a button click. So it would change the background image. However I cant get it to do this. Any ideas would be well received, as I'm guessing theres probably a javascript version that does it quicker and easier.
<html>
<head>
<title>Untitled</title>
<style>
#pictureframe {
width:200px;
height:200px;
}
.wooden {
background-image:url(frame.png);
}
.plain {
background-image:url(clear.png);
}
.black {
background-image:url(black.png);
}
</style>
</head>
<body>
<div id="pictureframe">
</div>
<div style="height:20px;border:1px solid #617779;width:90px;text-align:center;background-color:white;" onclick = "pictureframe.style.className = 'wooden'">Make it wood</div>
<br>
<div style="height:20px;border:1px solid #617779;width:90px;text-align:center;background-color:white;" onclick = "pictureframe.style.className = 'clear'">Make it Frameless</div>
<br>
<div style="height:20px;border:1px solid #617779;width:90px;text-align:center;background-color:white;" onclick = "pictureframe.style.className = 'wooden'">Make it Black Bezel</div>
</body>
className is not part of the style object in the DOM element, but a direct property:
document.getElementById("pictureframe").className = 'wooden';
It's not
pictureframe.style.className = ...
but
pictureframe.className = ...
DEMO
Try this:
onclick ="pictureframe.className = 'wooden'"
If you want to use some other class for style, than you probably need to go with something like this:
function replaceClass(className) {
$('#pictureframe').removeClass('plain black wooden');
return $('#pictureframe').addClass(className);
}​
This way you can keep class with styles http://jsfiddle.net/NjTea/5/

Categories