how to define html classes in javascript? - javascript

I have serval div's with classes and I want to define them in javascript.
Here is my jsfiddle script, It's only using DIV ID now but it has to be classes because I want to Add multiple blocks.
Can someone help?
var block = document.getElementById('block');
var minimizewindow = document.getElementById('minimizewindow');
block.style.height = "250px";
minimizewindow.style.display = "none";
//function minimize
minimize.onclick = function(){
if(block.style.height == "250px") {
block.style.display = "none";
} .........
http://jsfiddle.net/uVSyX/
click on the broken images for : minimize, maximze, close
Thank you!
EDIT : Think I don't get it, I wan't to show and hide multiple div's...

document.getElementsByClassName('myClass'); is the easiest way, however it is not supported by IE. Mozilla has great documentation on this.
If you need IE support, this page might be a good resource for you: http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/

and I want to define them in javascript.
this is a bad idea. Styling instructions belong in CSS style sheets.
The right way to go here would be having classes, like .expanded and .contracted
They would contain rules like
.expanded { width: 800px; display: block }
you then just change the class property in JavaScript. jQuery makes this very easy because it has convenient methods for dealing with classes.
http://api.jquery.com/hasClass/
http://api.jquery.com/addClass/
http://api.jquery.com/toggleClass/

I don't remember where I found this function at but it's what I've used to find elements based on class.
var elems = document.getElementsByTagName('div'),i;
for (i in elems) {
if((" "+elems[i].className+" ").indexOf(" "+matchClass+" ") > -1) {
elems[i].style.display = "none";
}
}
with matchClass being the name of the class you are looking for.
I updated the above code to set all div with a specific class that is defined as matchClass to be set to display:none when the function is run.

Related

Reveal Hidden Divs on click

I'm looking to reveal a div when I click on a corresponding div, much like when you click on an image in Google's image search results. The row of images split, and a new area is revealed. I got pretty far with my minimal knowledge of javascript here: http://codepen.io/anon/pen/fKEgw
The basics of it works like this:
document.getElementById("a-section").addEventListener("click", function () {
document.getElementById("a-reveal").style.height = "300px";
document.getElementById("b-reveal").style.height = "0px";
document.getElementById("c-reveal").style.height = "0px";
document.getElementById("d-reveal").style.height = "0px";
document.getElementById("e-reveal").style.height = "0px";
document.getElementById("f-reveal").style.height = "0px";
document.getElementById("g-reveal").style.height = "0px";
document.getElementById("h-reveal").style.height = "0px";
});
How can I get a similar effect without being forced to set a height value? Is there a better way to code this type of thing so I'm not making duplicate divs for the mobile view? SHould I use something other than just javascript?
Thank you very much for your help!
If you use jquery, you can simply do, for example
$("#a-reveal").show();
and
$("#b-reveal").hide();
rather than changing the heights. In plain javascript this is basically setting the 'display' css attribute to 'none' to hide it and then back (default is 'block').
edit:
Also, if you modify the html so that the divs are like this:
<div id="a-section" class="section" reveal="a-reveal">
....
<div id="a-reveal" class="reveal">
where reveal contains the ID of the associated reveal div, you could replace all the separate event handler attaching code with the following:
//attaches event to every div with class "section"
$(".section").click(function(){
$(".reveal").hide();
var thisRevealID = $(this).attr("reveal");
$("#"+thisRevealID).show();
});
There may be a cleaner way to get the appropriate reveal div than to resort to adding the reveal attribute, but the idea is to make it so you can determine what you need based on the clicked div without the code knowing exactly which div was clicked.
I agree that if the project is large you might be better off with JQuery, see thogue's excellent answer. If you want to stay with plain Javascript you can certainly clean it up a little bit:
var reveal_func = function(section){
var arr_a = new array("a-reveal","b-reveal","c-reveal");
for (var i=0; i<var_a.length; i++){
if (arr_a[i] === section){
document.getElementById(arr_a[i]).style.height = "300px";
}else{
document.getElementById(arr_a[i]).style.height = "0px";
}
}
};
and then
document.getElementById("a-section").addEventListener("click", reveal_func("a-reveal"))
document.getElementById("b-section").addEventListener("click", reveal_func("b-reveal"))
as needed.

How to search by classname and in element with style 'display='none''

My code
I have a problem with searching in javascript.
I need to look up both throughout the document and only the CSS class.
<span class="ID">153</span>
<span class="keywords">pararell processing, evolutionary algorithm, linear algebra algorithm, FPGA</span>
<span class="author">Oleg Maslennikow, </span>
I want to search g in Oleg but not in processing.
If i search i want to show hide elements, and after hide it..
In this case, I would like to be able to look after the class = 'author'.
I would also like to be able to look at the elements that have style display = 'none' by showing that element and then keep it.
Can anybody help me?
I dont want to use jQuery!
If you are using Chrome browser it should support document.querySelector()
This is how you achieve what you need :
document.querySelector('span.author'); // to return span class="author"
It is supported in the below browsers:
https://developer.mozilla.org/en-US/docs/DOM/Element.querySelectorAll
You could do something like this. No worries about the while-loop it's just a short and revers version of a for loop.
var element_to_find;
var list = document.getElementsByClassName("author");
var len = list.length;
while (len--) {
if (list[len].style.display == "none") {
var element_to_find = list[len];
alert("do what you want");
}
}
Second: You cold create a class for "display:none"
So it woud be easier to find.
Style:
.hidden{ display:none }

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.

changing css class model using JavaScript

Is it in any way possible, to change a css class model using JavaScript?
Pseudo code:
function updateClass(className, newData) {
cssInterface.alterClass(className, newData);
}
className being the name of the class, which is supposed to be changed (like ".footer") and newData being the new class content (like border: "1px solid pink;").
The target is, actually, just to save space: I am working with CSS3-animations, so changing one attribute of an element, which is affected by it's class, will terminate the animation of of it - The (in my case) font size won't change anymore. Using different classes will require an entire new set of classes for all affected elements, I'd like to avoid this.
I am not searching for a change via
element.className = "foo";
or
element.style.fontSize = "15pt";
Thanks for your help, guys :)
Here's my function to do this...
function changeCSS(typeAndClass, newRule, newValue) // modify the site CSS (if requred during scaling for smaller screen sizes)
{
var thisCSS=document.styleSheets[0] // get the CSS for the site as an array
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules // work out if the browser uses cssRules or not
for (i=0; i<ruleSearch.length; i++) // for every element in the CSS array
{
if(ruleSearch[i].selectorText==typeAndClass) // find the element that matches the type and class we are looking for
{
var target=ruleSearch[i] // create a variable to hold the specific CSS element
var typeExists = 1;
break; // and stop the loop
}
}
if (typeExists)
{
target.style[newRule] = newValue; // modify the desired class (typeAndClass) element (newRule) with its new value (newValue).
}
else
{
alert(typeAndClass + " does not exist.");
}
}
Called with (example)
changeCSS("div.headerfixed","-moz-transform-origin", "100% 0%");
hope this helps.
See my answer here. To answer your question: Yes, it's possible.
#CSS3: I tried exactly the same in one of my html5 experiments. I created an extra <style> element, and changed its contentText to the CSS class definitions I needed. Of course changing the cssRule object would be much cleaner :-)
As far as I can tell the CSS object model cannot easily tell you whether you already have an existing style rule for a particular class, but you can easily append a new rule for that class and it will override any previous declaration of that style.
I found an example of creating dynamic stylesheets.
You should take a look at dojo, it has some nice features where you can do just that..
require(["dojo/dom-class"], function(domClass){
// Add a class to some node:
domClass.add("someNode", "anewClass");
});
http://dojotoolkit.org/reference-guide/1.7/dojo/addClass.html

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