JS function doesn't change box color - javascript

JS just refuses to do anything - doesn't show console.log, doesn't show any errors, doesn't do anything.
JS just doesn't give any signs of life really - I tried making document.getelementbyid(box1) and ("#box") and ("box") because of people on the internet use all these and it works.
Tried to make events embedded in HTML to call the function, tried to call the function on window.onload, etc.
Tried changing text and color and size and margins - nothing works. And there is sometimes a null error - meaning that JS can't get the style value for some reason.
var box = document.getElementById("#box1");
function changeColor() {
var box = document.getElementById("#box1");
box.style.backgroundColor = 'red';
}
#box1 {
height: 100px;
width: 100px;
background-color: #B9E257;
}
#box2 {
height: 100px;
width: 100px;
background-color: #69ADE1;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="N.css" type="text/css">
</head>
<body>
<div id="box1">1</div>
<div id="box2">2</div>
<button onclick="changeColor()">Go!</button>
<script src="N.js" type="text/javascript"></script>
</body>
</html>
Why on earth would it not work?

The Document method getElementById() returns an Element object
representing the element whose id property matches the specified
string. Since element IDs are required to be unique if specified,
they're a useful way to get access to a specific element quickly.
For more info visit the docs
The ID is case-sensitive string which is unique within the document;
Please check the running example below:
function changeColor() {
var box = document.getElementById("box1");
console.log(box);
box.style.backgroundColor = 'red';
}
#box1 {
height: 100px;
width: 100px;
background-color: #B9E257;
}
#box2 {
height: 100px;
width: 100px;
background-color: #69ADE1;
}
<head>
<link rel="stylesheet" href="N.css" type="text/css">
</head>
<body>
<div id="box1">1</div>
<div id="box2">2</div>
<button onclick="changeColor()">Go!</button>
<script src="N.js" type="text/javascript"></script>
</body>

Your JS throwing error just because you are using # in document.getElementById which is not allowed. You need to define # for ID in jQuery not in JS.
Here is the updated code. Just only removed # from document.getElementById nothing else I have done in it.
function changeColor() {
var box = document.getElementById("#box1");
box.style.backgroundColor = 'red';
}
#box1 {
height: 100px;
width: 100px;
background-color: #B9E257;
}
#box2 {
height: 100px;
width: 100px;
background-color: #69ADE1;
}
<head>
<link rel="stylesheet" href="N.css" type="text/css">
</head>
<body>
<div id="box1">1</div>
<div id="box2">2</div>
<button onclick="changeColor()">Go!</button>
<script src="N.js" type="text/javascript"></script>
</body>

If you really like that #, then instead of
var box = document.getElementById("#box1");
do
var box = document.querySelector("#box1");

Related

jQuery resizable() for dynamic elements working uptil second-last element but not for the last element

I am creating div elements dynamically, on clicking on duplicate button. the divs are draggable and resizable horizontally. Everytime I create a new div, by clicking on duplicate, the new divs are draggable. But with resizable an unusual behavior is observed. The behavior is all the divs uptil second last div gets the resizable feature, but the most recent(last) doesn't get resizable. I referred the solution given here,
Apply jQueryUI Resizable widget to dynamically created elements. They are using :last and after() methods.
I am not getting how I use it in my case.
Following is my code,
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"
integrity="sha256-0YPKAwZP7Mp3ALMRVB2i8GXeEndvCq3eSl/WsAl1Ryk="
crossorigin="anonymous"></script>
<script type="text/javascript">
var bar_id = 1;
$(document).ready(function(){
$(".action").draggable({cursor:"move",containment:"#limits"});
$(".action").resizable({handles:"e,w",maxWidth:1300,maxHeight:46,minWidth:100,minHeight:46});
$(document).on('click',".duplicate_btn",function(){
bar_id += 1;
var duplicate_bar = $(this).parent().clone();
duplicate_bar.attr("id","action_"+bar_id);
duplicate_bar.find(".duplicate_btn").attr("id","duplicate_btn_"+bar_id);
$("#limits").append(duplicate_bar);
$(".action").draggable({cursor:"move",containment:"#limits"});
$(".action").resizable({handles:"e,w",maxWidth:1300,maxHeight:46,minWidth:100,minHeight:46});
});
});
</script>
<style type="text/css">
.action{
background-color: #aaa;
height: 46px;
width: 200px;
float:left;
border:2px solid black;
position:absolute;
/*for items inside div*/
display: flex;
align-items: center;
justify-content: center;
}
#limits{
background-color: lavender;
height: 50px;
width: 1300px;
}
</style>
</head>
<body>
<div id="limits">
<div id="action_1" class="action">
<button id="duplicate_btn_1" class="duplicate_btn">Duplicate</button>
</div>
</div>
</body>
</html>
Please help to get the way out. Thank You in advance!.
If you check the DOM inspector after you clone() the element you'll see that it has also copied the .ui-resizable-handle elements which were added to the original element when draggable() and resizable() were called on it.
This is the cause of the issue. You need to remove those elements before you define draggable and resizable on the new element. Also note that you can call those methods on the new instance directly instead of redefining the plugin on all instances of .action. Try this:
var bar_id = 1;
$(document).ready(function() {
defineDragResize($('.action'));
$(document).on('click', ".duplicate_btn", function() {
bar_id += 1;
var $duplicate_bar = $(this).parent().clone().appendTo('#limits')
$duplicate_bar.find('div').remove();
defineDragResize($duplicate_bar);
});
function defineDragResize($el) {
$el.draggable({
cursor: "move",
containment: "#limits"
}).resizable({
handles: "e,w",
maxWidth: 1300,
maxHeight: 46,
minWidth: 100,
minHeight: 46
});
}
});
.action {
background-color: #aaa;
height: 46px;
width: 200px;
float: left;
border: 2px solid black;
position: absolute;
/*for items inside div*/
display: flex;
align-items: center;
justify-content: center;
}
#limits {
background-color: lavender;
height: 50px;
width: 1300px;
}
#limits {
background-color: lavender;
height: 50px;
width: 1300px;
}
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js" integrity="sha256-0YPKAwZP7Mp3ALMRVB2i8GXeEndvCq3eSl/WsAl1Ryk=" crossorigin="anonymous"></script>
<div id="limits">
<div class="action">
<button class="duplicate_btn">Duplicate</button>
</div>
</div>
One thing to note is that I removed the dynamic id logic. This is an anti-pattern and should not be used. Use common classes and DOM traversal instead.

How to pass the color of this element to javascript without using inline stylesheet?

My question is very similar to this one in that I need to pass the background color that an element has to a javascript function. The difference is that I want the color to be defined outside the element itself, in a stylesheet:
<!DOCTYPE html>
<html>
<head>
<style>
button.red_button {
background: red;
cursor: pointer;
border: none;
width: 48px;
height: 48px;
}
</style>
</head>
<body>
<button class="red_button" onclick="javascript:changeColor(this)"></button>
<p id="change_me">Click on the red box to change this text to red!</p>
<script>
function changeColor(button) {
document.getElementById("change_me").style.color = button.style.background;
}
</script>
</body>
</html>
It works fine when the background color is defined inline, but can't seem to find it when it's declared externally.
You can use getComputedStyle method to get the all the styles applied on the button. Then apply it to the text
function changeColor(button) {
var style = window.getComputedStyle(button);
document.getElementById("change_me").style.color = style['background-color'];
}
DEMO
As #nnnnnn mentioned you can use getComputedStyle() to get the CSS of your element, simply .style only gets the inline style attribute of the element:
function changeColor(button) {
document.getElementById("change_me").style.color = getComputedStyle(button)['background-color'];
}
<!DOCTYPE html>
<html>
<head>
<style>
button.red_button {
background: red;
cursor: pointer;
border: none;
width: 48px;
height: 48px;
}
</style>
</head>
<body>
<button class="red_button" onclick="changeColor('#ff0000');"></button>
<p id="change_me">Click on the red box to change this text to red!</p>
<script>
function changeColor(color) {
document.getElementById("change_me").style.color = color;
}
</script>
</body>
</html>
what I did is I changed a bit of the script so that you set the color on the function, and it colors the place automatically

On click goes to next page - JavaScript

Hello I have one confusion in my head.
I'm trying to make a logic in JS when some one click on BUTTON then automatically lead to next page after 1s.
I tried to use onclick function but I'm getting error.
I included simple html and css in purpose of texting.
Can some one help me.
Also That logic must apply to any pages.
Cheers!
#btn {
position: relative;
width: 300px;
height: 80px;
content: 'Button';
background: blue;
border-radius: 9px;
color: white;
vertical-align: center;
}
#next {
position: relative;
width: 300px;
height: 80px;
content: 'Button';
background: blue;
border-radius: 9px;
color: white;
margin-top:50px;
}
#text {
margin:auto;
position: relative;
width: 80px;
height: 40px;
padding-top: 30px;
}
<<!DOCTYPE html>
<html>
<head>
<title>!!!AAA!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="btn"><div id="text">Button</div></div>
<div id="next"><div id="text">next</div></div>
</body>
</html>
To go to a different page after 1 second you'll want to use a combination of setTimeout() and window.location and an onclick event on your button.
I am assuming you want to use the button next to make this happen.
First thing create a second html test page.
<html>
<body>
<h1>Page 2</h1>
</body>
</html>
and in the code you shared, after the closing </div> tag for id next add the following:
<!DOCTYPE html>
<html>
<head>
<title>!!!AAA!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="btn">
<div id="text">Button</div>
</div>
<div id="nextPage">
<button id="next" onclick="switchLocation(0)">next</button>
</div>
<script>
function switchLocation(counter) {
if (counter == 0) {
counter = 1;
setTimeout(function() {
switchLocation(counter);
}, 1000);
} else {
window.location = "page2.html";
}
}
</script>
</body>
</html>
I edited your code slightly. Removed the extra < on the first line and changed the "next" div to a button.

How to place one element exactly to the same visible position, as another?

I have two elements "src" and "dest"
"src" and "dest" are in different DOM-nodes, that can not have the same parent.
I need to place "src" element in the same visible position, as "dest".
"src" element must also have the same sizes, as "dest".
I have following code for case, when "src" and "dest" having the same parent:
src.css("position", "absolute");
src.css("top", dest.offset().top);
src.css("left", dest.offset().left);
src.width(dest.width());
// Show "src" element, instead of "dest". "src" must be in the same visible position, as "dest"
dest.css("opacity", 0);
src.show();
Unfortunately, it does not works. "src" element has displacement to bottom and left, for that i cannot find the reason.
Maybe, i do something wrong ...
How to do it right for two cases ?
"src" and "dest" having the same grand-parent
"src" and "dest" does't having the same parent. Maybe grand-grand-grand-parent is the common for both.
Update:
I have arranged a simple HMTL document, that does a simple visual swapping of one element with another:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MacBlog</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js" charset="utf-8"></script>
<style type="text/css" media="screen">
.dest {
background-color: #0cf;
width: 480px;
height: 320px;
}
.src {
background-color: #09c;
width: 1024px;
height: 768px;
}
</style>
<script type="text/javascript" charset="utf-8">
jQuery(function($){
// Common items, to deal with
var src = $(".src");
var dest = $(".dest");
// Setup
src.hide();
// Interaction
dest.click(function(){
src.width(dest.width());
src.height(dest.height());
src.offset(dest.offset());
dest.hide();
src.show();
});
});
</script>
</head>
<body>
<div>
<!--On clicking, this element should visually be swapped by ".src" element -->
<div class="dest"><p>dest</p></div>
<div class="src"><p>src</p></div>
</div>
</body>
</html>
It does not work correctly. After "swapping", "src" element has a strange displacement to top-left direction on ~30 pixels.
I use latest version of Safari 5, if i makes sense.
Update 2:
Unfortunately, this also does not works. I updated my example:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MacBlog</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js" charset="utf-8"></script>
<style type="text/css" media="screen">
div {
margin: 0;
padding: 0;
}
.holder {
position: relative;
top: 40pt;
left: 40pt;
border: black solid thin;
}
.dest {
background-color: #0cf;
width: 480px;
height: 320px;
}
.src {
background-color: #09c;
width: 1024px;
height: 768px;
}
</style>
<script type="text/javascript" charset="utf-8">
jQuery(function($){
// Common items, to deal with
var src = $(".src");
var dest = $(".dest");
// Setup
src.hide();
// Interaction
dest.click(function(){
src.css("position", "absolute");
src.width(dest.width());
src.height(dest.height());
src.offset(dest.offset());
dest.hide();
src.show();
});
});
</script>
</head>
<body>
<div class="holder">
<!--On clicking, this element should visually be swapped by ".src" element -->
<div class="dest"><p>dest</p></div>
<div class="src"><p>src</p></div>
</div>
</body>
</html>
I tested it here:http://jsfiddle.net/YEzWj/1/
Using your second example make your CSS like this:
div {
position:relative;
margin: 0;
padding: 0;
}
.holder {
position: relative;
top: 40pt;
left: 40pt;
border: black solid thin;
}
.dest {
position:absolute;
background-color: #0cf;
width: 480px;
height: 320px;
}
.src {
background-color: #09c;
width: 1024px;
height: 768px;
}
EDIT: After playing around with it some, it did not work in all circumstances. I decided to change the javascript. Note: My example toggles the display of src and dest within the holder, making holder the same size as dest so the border shows outside the dest and src.
jQuery(function($){
// Common items, to deal with
var src = $(".src");
var dest = $(".dest");
var holder=$(".holder");
holder.width(dest.width());
holder.height(dest.height());
// Setup
src.hide();
// Interaction
dest.click(function(){
src.show();
src.css("position", "absolute");
src.width(dest.width());
src.height(dest.height());
src.offset(dest.offset());
dest.hide();
});
src.click(function(){
dest.show();
src.hide();
});
});
EDIT2: Remove the src.click() event if you wish it to NOT go back to the dest on src click.
You need to make the dest element absolute, otherwise the top and left offsets will not apply.
src.css('position', 'absolute'); // ensure position is set to absolute
src.offset(dest.offset());
Also, elements like p and body will have default stylesheets depending on browser. So try to supply a reset style to make things consistent:
p {
margin: 0;
}
body {
margin: 0;
padding: 0;
}
You can call the offset function to set the offset and handle different parents correctly, like this:
dest.offset(src.offset());

Javascript style variables with "-" in their name aren't able to be changed?

Okay, so this bug has cost me quite a bit of time and embarrassment. It seems that any style variable with a - in it's name can't be modified by javascript.
As seen here:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Class Test</title>
<meta charset="utf-8" />
<style>
body { text-align: center; background-color: #ffffff;}
#box { position: absolute; left: 610px; top: 80px; height: 50px; width: 50px; background-color: #ff0000; color: #000000;}
</style>
<script type="text/javascript">
var box = 0;
</script>
</head>
<body>
<div id="box" ></div>
<script type="text/javascript">
box = document.getElementById('box');
box.style.background-color = "#0000ff";
</script>
</body>
</html>
The box in said example will just remain red.
So how do I change a style variable with a - in it's name?
backgroundColor, camelCase.
background-color literally means "the value in background, minus the value in color"
You want backgroundColor
More info...

Categories

Resources