Skip to content Skip to sidebar Skip to footer

Javascript Modify Style Of An Element

As a newbie to javascript I am trying to code a function that adds yellow divs to page (like post-its) wherever the user clicks. Event handling seems fine, but somehow the style pr

Solution 1:

Some basic demo:

window.onclick = function ( e ) {
    if ( e.target.className === 'postit' ) { return; }
    var div = document.createElement( 'div' );
    div.contentEditable = true;
    div.className = 'postit';
    div.style.left = e.clientX + 'px';
    div.style.top = e.clientY + 'px';
    document.body.appendChild( div );
};

Live demo:http://jsfiddle.net/4kjgP/1/

Solution 2:

The div you are creating has no size so it won't be visible even if the rest of the code works as desired. Then, once you give it some size, there is no content so you still may not see it.

The color style attribute applies to text in the div and you have no text so you won't see any yellow. If you want a yellow block, you should set the background color to yellow (after you set a size) with .style.backgroundColor = "yellow".

Solution 3:

if you want to add yellow divs, you might be actually thinking of adding yellow colored divs? Code you are using should make text in them yellow. if you want bg to be yellow, use style.backgroundColor instead. Also give your div some width and height, or alternatively, give it some content, else it might now show.

Solution 4:

<div> with no content inside and no size will usually be skipped by browser rendering. You'll probably also need to put another element inside of it (like a <p> with lorem ipsum) to see something appear.

For real-time editing and playing with this stuff, check out JSFiddle

This also doesn't do what you want. Setting the color will make the text yellow, not the post it note effect. For that, use background. Check out this re-worked solution.

Post a Comment for "Javascript Modify Style Of An Element"