object.style.left returns nothing in javascript? - javascript

I am unable to access the left position of an image element. Here is the my jsFiddle.
The alert box is displaying nothing.
<!DOCTYPE html>
<html>
<img src="pan.jpg" id="uno" width="600" />
<style>
#uno
{
position:relative;
left:100px;
}
</style>
<script>
alert(document.getElementById("uno").style.left);
</script>
</html>

JavaScript's style property only has access to inline styles. You'll notice it works with this: (jsFiddle)
<img src="pan.jpg" id="uno" width="600" style="left:125px;" />
I suggest you either only set left in JavaScript or use classes in CSS and check the object for the class instead of the style.

Alternate Solution(if you do not define inline styles, little complicated though)
//document.styleSheets gives the list of available stylesheets for the document
//Here we have only one stylesheet hence document.stylesheets["0"] gives us the only stylesheet
//document.stylesheets["0"].rules gives the object with defined css rules
var rules = document.styleSheets["0"].rules
//iterating over that object to find the object which has css for element ID "uno"
for(property in rules){
if(rules.hasOwnProperty(property)){
if(rules[property].selectorText === "#uno"){
alert(rules[property].style.left);
}
}
}
Updated File
<!DOCTYPE html>
<html>
<img src="pan.jpg" id="uno" width="600" />
<style>
#uno
{
position:relative;
left:100px;
}
</style>
<script>
var rules = document.styleSheets["0"].rules
for(property in rules){
if(rules.hasOwnProperty(property)){
if(rules[property].selectorText === "#uno"){
alert(rules[property].style.left);
}
}
}
</script>
</html>
rather use jquery which does all the hardlifting for us

Related

Create highlight effect on hover an element

I tried to make highlight effect on each <a> element while I hover on each div element but it doesn't work and console shows this error
"Uncaught TypeError: Cannot set property 'background' of undefined
at highlight_function"
enter image description here
function highlight_function () {document.getElementsByTagName("a").style.background="#80ff00"};
document.getElementsByTagName("div").addEventListener("mouseover",highlight_function())
I think it's because document.getElementsByTagName("a") is an array, and you are trying to set style on the array and not in each element.
You should either make a for loop to change background style of each element or add a style tag like a {background: "#80ff00"}.
But you can't define style to an array like this
index.html
<html lang="en">
<head>
</head>
<body>
<div>
something
</div>
</body>
<script>
function highlight_function() {
const a = document.querySelector('a');
a.style.background = "#80ff00"
}
const div = document.querySelector('div');
div.addEventListener('mouseover', highlight_function);
</script>
</html>
I don't think background property will work on an <a> tag. Try doing this in your function:
document.getElementsByTagName("a").style.color="#80ff00"
Here is you can try this
function highlight_function() {
document.getElementById("a").style.backgroundColor = "#80ff00";
};
<div id="div">
<a id="a" onmouseover="highlight_function()">Hell</a>
</div>
when you make this call
document.getElementsByTagName("a")
it will return to you collection of html elements so there is no style property
you can use for loop through it
for(var a of document.getElementsByTagName("a")) {
a.style.background="#80ff00";
}
you can simply add highlight effect or change the background color by adding the CSS as follows:
<!DOCTYPE html>
<html>
<head>
<style>
p:hover {
background-color: green;
}
</style>
</head>
<body>
<p id="hometown">I live in Pakistan</p>
</body>
</html>

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.

Javascript- creating element as a child of another element

Hello here's my simple code.I want to display image created in function add(src){} in element main_container.Why doesn't it work?
<head>
</head>
<body>
<style>
#main_container
{
width:1000px;
height:1000px;
position:absolute;
border-style:solid;
}
.jersey
{
width:100px;
height:150px;
position:absolute;
}
</style>
<script>
var dist=-110;
function add(src)
{
dist=dist+110;
var img=document.createElement("img");
img.src=src;
img.style.left=dist+"px";
img.className="jersey";
document.getElementById("main_container").appendChild(img);
}
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
</script>
<div id="main_container"></div>
</body>
</html>
Move the script tag below the element.
Change:
<script>...</script>
<div id="main_container"></div>
To:
<div id="main_container"></div>
<script>...</script>
The browser reads HTML from top to bottom.
beautifulcoder's suggested modification should work, and he is absolutely correct that this is happening because the main_container DOM element will not yet be loaded if it appears after the <script>, but ideally, you should hold off on making DOM manipulations until the document has loaded. You can do this by using the window.onload event:
<script>
function add(src) {
...
}
function initialize() {
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
}
window.onload = initialize;
</script>
<div id="main_container"></div>
or even better, use jQuery's ready event:
function initialize() {
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
}
$(document).ready(initialize);
// $(initialize); <- Shorthand version
Either of these approaches will free you from having to worry about where your script blocks are relative to your page elements.

Javascript change width of image onclick

I'm a complete noob when it comes to javascript. Would there be anyway to change an image after it is clicked, some way to trigger a js function to change the css. It would have to be triggered by an event and something other than onclick, onfocus probably.
<style>
#pic {
width:100px;
height:100px;
}
</style>
</head>
<body>
<img src='nope.jpg' id='pic' onclick="mouseOver()"></img>
<script type='text/javascript'>
function mouseOver() {
document.getElementById('pic').style.width="400px";
document.getElementById('pic').style.height="400px";
}
</script>
try this...
function mouseOver() {
document.getElementById('image').style.height = "400px";
}
First i edited the question , because the function was not defined correctly .
Second :
to access the height property of any element , you should use style.height , and should add "px" to the value.
please spend more time searching for answers , instead of posting a new question.
Change the JS to this:
var image = document.getElementById('image');
function mouseOver() {
image.style.height="600px";
}
image.onclick = mouseOver;
Setting values you can use directly style attribute, but remember that asking for them is a greater problem:
Please refer to this one:
Get a CSS value with JavaScript
This should work
<style>
#pic {
width:100px;
height:100px;
}
</style>
</head>
<body>
<img
width="100"
onmouseOver="this.width=400; this.height=400"
onclick="this.width=100"
alt="RESIZE IMAGE"
id='pic'
src='nope.jpg'
/>
just copy and edit the image tag code as needed

Cloning div and changing attributes

I performed various research but I din't find a solution for my problem. I created a drop down select with css to change color of background, but then when I try to clone it with Javascript, the new copy doesn't change attributes in selection so it keep the original color. Just try it, add some copy and try to change the colors.
I'm new here, i'm not very able to add code so here's to try:
http://jsfiddle.net/gabry501/FUyA3/
or github
https://github.com/gabry501/Test-Color/blob/master/test.html
HEAD
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function cloning() {
var container = document.getElementById('fine');
var clone = document.getElementById('contenitore').cloneNode(true);
container.appendChild (clone);
}
STYLE
select option,
select {
background-color:white;
width:200px;
height:200px;
}
select option[value="1"],
select.o1
{
background-color:blue;
}
select option[value="2"],
select.o2
{
background-color:red;
}
select option[value="3"],
select.o3
{
background-color:orange;
}
BODY
<div style="width:1100px;
height:250px;" id="contenitore">
SCRIPT
<script>$('select[id$=-status][id^=id_item-]').children().each(
function (){
if($(this).val() == 0){
$(this).css('backgroundColor','white');
}
if($(this).val() == 1){
$(this).css('backgroundColor','green');
}
if($(this).val() == 2){
$(this).css('backgroundColor','red');
}
if($(this).val() == 3){
$(this).css('backgroundColor','orange');
}
}
);</script>
<script>
$('select[id$=-status][id^=id_item-]').change(function (){
var color = $(this).find('option:selected').val();
$(this).removeClass('o1 o2 o3').addClass('o' + $(this).find('option:selected').val());
}).change();
It seems you are depending on a listener to modify the style. Listeners added using addEventListener are not included in a cloned element, you have to attach them seperately.
Note that listeners added inline, or using attachEvent are cloned.
cloneNode() copies only the data of the element in question. it does not copy over the event listeners. You need to do that manually..
Use the jQuery clone() method..
function cloning() {
var container = document.getElementById('fine');
var clone = $(document.getElementById('contenitore')).clone(true);
$(container).append(clone);
}
Check Fiddle
PS : Also you code looks really messy . You can scale it down..
UPDATE
I have made a few changes to the code .
1.) Removed the click event from HTML and added that to the script.
2.) Removed the ID's and replaced by a className as ID's in a document are supposed to
be Unique.
3.) Removed extra styles and replaced with a simple class Name.
4.) Better to have separate files for style and script than including it in HTML.
5.) If you want it to work , move the styles and the script to the corresponding tags I
have marked..
HTML
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style type="text/css">
// Add the Styles here
</style>
</head>
<body>
<div style="width:1100px; height:250px;" class="contenitore">
<select name="item-0-status">
<option value="" disabled="disabled" class="optionGroup">SELECT
COLOR</option>
<option value="1"> BLUE</option>
<option value="2"> RED </option>
<option value="3"> ORANGE</option>
</select>
</div> <!--Contenitore -->
<div id="fine"></div>
<br>
<div id="bottone">
<input id="btn" type="button" Value="ADD">
</div>
<script type="text/javascript">
// Script Comes Here
</script>
</body>
</html>
Javascript
$(function() {
$('select[name="item-0-status"]').change(function() {
$(this).removeClass('o1 o2 o3').addClass('o' + $(this).val());
}).change();
$('#btn').on('click', function() {
var container = document.getElementById('fine');
var clone = $(document.getElementsByClassName('contenitore')[0]).clone(true);
$(container).append(clone);
});
});​
Styles
#bottone
{
float:left;
text-align:left;
clear:left;
margin-top:20px;
}
select option,select
{
background-color:#FFF;
width:200px;
height:200px;
}
.o1
{
background-color:blue;
}
.o2
{
background-color:red;
}
.o3
{
background-color:orange;
}​
UPDATED FIDDLE
You have to use $('.el').live('change', fn) instead of $('.el').change(fn) because you're adding an element after the DOM is loaded.
See this jsfiddle: http://jsfiddle.net/FUyA3/1/
try deep cloning - i.e $(selector).clone(true)....then events will also be cloned

Categories