How to style with JavaScript - javascript

I am trying to use style attribute for JavaScript. But, apparently, I was doing something wrong with it. I am new in JavaScript so a general idea about style attribute for JavaScript would be great. I want to change the place, color and text-decoration etc. of JavaScript elements. I thought that declaring style attribute for div changeMe in HTML will be applied for the JavaScript. Because, JavaScript takes id of it. I wanted to use all of the style attributes that are in the div. Where am I missing? Here is my attempt to do it:
<div id="changeMe" style="position: absolute;text-decoration: none;
color: white;right:43%; top: 90px;">
<a href="home.php" >Go to homepage</a>
</div>
Javascript:
var testElement = document.getElementById("changeMe");
var text = "aaa".document.getElementById("changeMe");
text.style.textDecoration = "none"; //I changed style here too because first did not
//work.
check.onfocus= function()
{
testElement.innerHTML = text.link("index.php");;
}
Please help me understand the structure.I am stuck.Thanks

Your JavaScript will error here:
var text = "aaa".document.getElementById("changeMe");
…since "aaa" is a string and strings do not have a document property. The rest of the script won't execute.
If you fixed that line, then:
text.style.textDecoration = "none";
… would have no effect. The text-decoration is part of the link's style, not the div's.
You need to style the <a> element. If you really want to get to it via JS then you can:
testElement.getElementsByTagName('a')[0]
But you would probably be better off just using a stylesheet:
#changeMe a { text-decoration: none; }
But make sure you do something else to make it clear that the piece of non-underlined text is a link.

You're trying to style the div but you need to apply your text-decoration and color styles to the a tag itself for it to take effect.
All of this can easily be done with cascading style sheets instead, by the way.

document.getElementById("changeMe").firstChild.style.textDecoration = "none";
Working Example: http://jsfiddle.net/8Evyq/

Something definitely fishy here.
var text = "aaa".document.getElementById("changeMe");
// Without those "aaa"
var text = document.getElementById("changeMe");
// To change the <a> style inside the 'changeMe' <div>
var alinks = text.getElementsByTagName("a");
for (var i=0; i<alinks.length; i++) {
alinks[i].style.textDecoration = "none";
}
Here it is in action.

Related

The margins in div of new tab not at all taking effect

Hi I am creating dynamic form in new tab using JavaScript. Margin effects on div are not taking effect. I am neither able to set the margins using class and id in css nor using div.setAttribute. Below is the code.
`
var openWindow = window.open('dynForm.html','_blank','');
var windoc=openWindow.document;
windoc.write("This is dynamic form ");
var div=document.createElement("div");
div.setAttribute("style","border:solid");
div.setAttribute("style","margin-left:1cm");
div.setAttribute("style","margin-right:1cm");
div.setAttribute("style","margin-bottom:1cm");
div.setAttribute("style","margin-top:1cm");
div.setAttribute("style","background-color:lightblue");
`Only background color is taking effect on the new tab. The below screen shot shows how the screen looks irrespective of the values of margin.
Quesstion 2: No class or id attribute in my css is being applied to div.
#myDIV2{
background-color:lightblue;
}
I tried div.id="myDIV2";
I also tried div.setAttribute("id","myDIV2");` I applied the same using class also, but still couldn't find any difference. I do not know why its not working and what went wrong here. Please help
You're overriding the styles every time you call setAttribute, try combining the styles and then set the style attribute only once:
var openWindow = window.open('dynForm.html','_blank','');
var styles= [
"border:solid;",
"margin: 1cm;",
"background-color:lightblue;"
];
var windoc=openWindow.document;
windoc.write("This is dynamic form ");
var end_styles = "";
for (var i=0; i<styles.length;i++) {
end_styles += styles[i];
}
var div=document.createElement("div");
div.setAttribute("style", end_styles);
Note: the fiddle won't work on stackoverflow, I used it because it's easier to format code
This is happening because your all style attribute are getting overridden by previous div.setAttribute and your last attribute div.setAttribute("style","background-color:lightblue"); getting applied. Try to put all styles in one go. div.setAttribute("style","style1:value1;style2:value2;style3:value3;");

Adding CSS to and added input elements using Javascript

I'm new to JavaScript. I managed to add dynamic inputs after clicking on a button but I want to know how to apply the CSS to those added inputs, if anyone can give me a simple example i'd be glad!
Thank you!
Perhaps something like this:
<button onclick="newInput()">Add new input</button>
function newInput() {
var newElement = document.createElement("input");
newElement.className = "newClass";
document.body.appendChild(newElement);
}
And in the style section, or in the .css file, you'll have:
.newClass {
/*Styles go here*/
display: block;
}
Fiddle example of the above: http://jsfiddle.net/8zen9wwo/3/
Here is a very simple example using jQuery:
http://jsfiddle.net/kmrvpz99/
Html Code
<div class="container"></div>
Javascript Code
$('.container').append('<input type="text" class="yourstyle">');
var manualCss = $('<input type="text">').css('background-color', '#333');
$('.container').append(manualCss);
The css File
.yourstyle {
background-color: #000;
}
By defining .yourstyle in the css file, all elements on the html site that possess this class, even those dynamically added via javascript, will use this style. You can however manually modify the css by setting the style attribute on the element directly.

javascript-- changing the innerHTML of an image

So I JUST asked a question and I've already hit another roadblock. Thanks so much to the stackoverflow community for helping me out so much recently :)
Every time I see people changing the innerHTML of some tag, they use document.getElementByID(id).innerHTML. My images do NOT have ids, nor do I want to give each and every one of them an id.
Here is my code:
function clickImages()
{
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++)
{
var delegate = function() { hover(this); };
images[i].onmouseover = delegate;
}
}
function hover(img)
{
img.innerHTML = "Text!";
}
The innerHTML doesn't seem like it's working; when I mouse over the image nothing changes.
Thanks in advance! Let me know if I can clarify!
An image is itself a replaced element, so there is no innerHTML to replace.
Based on your comment, if you want to add HTML adjacent to the image, you could do this:
img.insertAdjacentHTML('afterend', 'HTML code');
You could also change 'afterend' to 'beforebegin' if you wanted to add the HTML before the image.
Writing on the image itself would be much more complicated and would require positioning another element above it with a transparent background, or using the image itself as the background of another element, or a variety of other similar techniques.
Element.innerHTML
innerHTML sets or gets the HTML syntax describing the element's
descendants
innerHTML means the HTML that comes between the start and end HTML tags. Images don't have innerHTML
I am not sure what you want to achieve.
If you want to have a text displayed onmouseover, you can use the title attribute to do that.. for example:
<img src="smiley.gif" alt="Smiley face" title="Hello" />
If you are trying to replace the image with text on onmouseover ... then as an example (only to show the possibilities), the following code will hide the image & display a text onmouseover and make the image visible & remove the text onmouseout (although not very satisfactorily IMHO, more work has to be done on the code to improve it)
Please note: There shouldn't be any gap between the image tag and the span for this particular code to work. Also, a negative margin-left added to the span element can make it appear over the location of the image.
<img onmouseover="toText(this)" onmouseout="toImage(this)" src="smiley.gif" alt="Smiley" /><span style="visibility: hidden; margin-left: -30px;">Show Text</span>
function toText(img) {
img.style.visibility = 'hidden';
img.nextSibling.style.visibility = 'visible';
}
function toImage(img) {
img.style.visibility = 'visible';
img.nextSibling.style.visibility = 'hidden';
}
Good luck
:)

How to dynamically set and modify CSS in JavaScript?

I have some JavaScript code that creates some div elements and it sets their CSS properties.
Because I would like to decouple CSS logic from my JavaScript code and because CSS is easier to read in its own .css file, I would like to set the CSS className of my element and then dynamically inject some values into the defined CSS property.
Here is what I would like to do :
style.css:
.myClass {
width: $insertedFromJS
}
script.js:
var myElement = document.createElement("div");
myElement.className = "myClass";
I want to do something like this but at that point myElement.style.width is empty
myElement.style.width.replaceAll("$insertedFromJS", "400px");
I think my problem here is that after the call to myElement.className = "myClass", the CSS is not yet applied.
If I understand your question properly, it sounds like you're trying to set placeholder text in your css file, and then use javascript to parse out the text with the css value you want to set for that class. You can't do that in the way you're trying to do it. In order to do that, you'd have to grab the content of the CSS file out of the dom, manipulate the text, and then save it back to the DOM. But that's a really overly-complicated way to go about doing something that...
myElement.style.width = "400px";
...can do for you in a couple of seconds. I know it doesn't really address the issue of decoupling css from js, but there's not really a whole lot you can do about that. You're trying to set css dynamically, after all.
Depending on what you're trying to accomplish, you might want to try defining multiple classes and just changing the className property in your js.
Setting the style, might be accomplished defining the inner-page style declaration.
Here is what i mean
var style = document.createElement('style');
style.type = 'text/css';
style.cssText = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementById('someElementId').className = 'cssClass';
However the part of modifying it can be a lot of tricky than you think. Some regex solutions might do a good job. But here is another way, I found.
if (!document.styleSheets) return;
var csses = new Array();
if (document.styleSheets[0].cssRules) // Standards Compliant {
csses = document.styleSheets[0].cssRules;
}
else {
csses = document.styleSheets[0].rules; // IE
}
for (i=0;i<csses.length;i++) {
if ((csses[i].selectorText.toLowerCase()=='.cssClass') || (thecss[i].selectorText.toLowerCase()=='.borders'))
{
thecss[i].style.cssText="color:#000";
}
}
could you use jQuery on this? You could use
$(".class").css("property", val); /* or use the .width property */
There is a jQuery plugin called jQuery Rule,
http://flesler.blogspot.com/2007/11/jqueryrule.html
I tried it to dynamically set some div sizes of a board game. It works in FireFox, not in Chrome. I didn't try IE9.

How do you change the background color of an <input> element with javascript

I have a <input> element that I want to change the background color on. The code I am currently using is this (but it is not working):
var allBlanksLoc = document.getElementById('text');
var allBlanks = allBlanksLoc.getElementsByTagName('input');
for(i=0; i<allBlanks.length; i++) {
var currentBlank = allBlanks[i];
var wordNum = blanks[i];
var blankWord = text[wordNum];
var usrAnswer = currentBlank.value;
if (usrAnswer != blankWord) {
currentBlank.style.backgroundColor = "red";
}
}
The third to last line being the most important
Update:
I fixed the camelCase on it but it still does not work. Any ideas of bugs there?
The full code is here: http://jsbin.com/imolo3/edit
Case is important. What you need is
document.getElementById('test').style.backgroundColor='red';
However
it would be better to use a css rule and use javascript only to add the class to the element.
CSS Rule
input.invalid {
background-color: red;
}
Javascript
element.className = 'invalid';
It should be backgroundColor - notice the capital C, JavaScript is case-sensitive.
Are you sure that this script is running at the right time? If it runs before the page is fully formed, the appropriate elements might not be present.
So not to repeat the solutions other users gave.
I personally use JQuery (and it's where any javascripter ends, overall for browser compatibility issues), and it would:
$(currentBlank).css("background-color","red");

Categories

Resources