Jump to content

Javascript wont respond to classes


612wharfavenue

Recommended Posts

Im trying various ways to trigger a transition, the simplest being the use of css pseudoclasses:

//leaving out default header stuff//<head><style>.item{opacity:1;-moz-transition: opacity 1s ease;}.item:hover {opacity:0;}</style></head><body><img src="myimage.jpg" class="item" /></body>

If i use js to make it trigger onclick instead of hover it works fine:

//leaving out default header stuff//<head><style>#item{opacity:1;-moz-transition: opacity 1s ease;}</style><script type="text/javascript">function transition() {			document.getElementById('item').style.opacity="0";}</script></head><body><img src="myimage.jpg" id="item" onclick="transition()" /></body>

But if i replace the id's with classes, it no longer works:

//leaving out default header stuff//<head><style>.item{opacity:1;-moz-transition: opacity 1s ease;}</style><script type="text/javascript">function transition() {			document.getElementsByClassName('item').style.opacity="0";}</script></head><body><img src="myimage.jpg" class="item" onclick="transition()" /></body>

What am i doing wrong?

Link to comment
Share on other sites

What browser are you using? Are you getting any Javascript errors? getElementsByClassName might not be supported in your browser. Otherwise, it should return an array of elements. You'll need to loop through the array and apply the style to each element.

Link to comment
Share on other sites

Im trying various ways to trigger a transition, the simplest being the use of css pseudoclasses:
//leaving out default header stuff//<head><style>.item{opacity:1;-moz-transition: opacity 1s ease;}.item:hover {opacity:0;}</style></head><body><img src="myimage.jpg" class="item" /></body>

If i use js to make it trigger onclick instead of hover it works fine:

//leaving out default header stuff//<head><style>#item{opacity:1;-moz-transition: opacity 1s ease;}</style><script type="text/javascript">function transition() {			document.getElementById('item').style.opacity="0";}</script></head><body><img src="myimage.jpg" id="item" onclick="transition()" /></body>

But if i replace the id's with classes, it no longer works:

//leaving out default header stuff//<head><style>.item{opacity:1;-moz-transition: opacity 1s ease;}</style><script type="text/javascript">function transition() {			document.getElementsByClassName('item').style.opacity="0";}</script></head><body><img src="myimage.jpg" class="item" onclick="transition()" /></body>

What am i doing wrong?

I think it's because of an incorrect use of getElementsByClassName. it returns a list of elements, so I don't think you can just set their properties like that. You might want to try something like this:
<script type="text/javascript">function transition() {  var elements = document.getElementsByClassName('item').style.opacity="0";  for(var i = 0, l = elements.length; i < l; i++){	elements[i].style.opacity = "0";  };};</script>

https://developer.mozilla.org/En/DOM/Docume...entsByClassNameedit: also make note of the browser you are using like JSG pointed out.

Link to comment
Share on other sites

Im testing this with FF4b9. Loop through the elements? umm....isnt there a simplier way of doing this? I cant make sense of what this script does, much less how to apply it to my site.

<script type="text/javascript">function transition() {  var elements = document.getElementsByClassName('item').style.opacity="0";  for(var i = 0, l = elements.length; i < l; i++){	elements[i].style.opacity = "0";  };};</script>

Link to comment
Share on other sites

The script you posted has an error, so it does nothing. If you . . .

change this line:var elements = document.getElementsByClassName('item').style.opacity="0";to this:var elements = document.getElementsByClassName('item');

the script will make every element with classname "item" completely transparent (invisible).

Link to comment
Share on other sites

As to making things simple, that's actually what loops were designed for. Developers use loops all the time.Your script could be simpler if you want to learn an add-on library like jQuery, but the code that jQuery executes will use a loop of some kind, so the overall complexity of the code would be a little greater, not less.

Link to comment
Share on other sites

Im testing this with FF4b9. Loop through the elements? umm....isnt there a simplier way of doing this? I cant make sense of what this script does, much less how to apply it to my site.
<script type="text/javascript">function transition() {  var elements = document.getElementsByClassName('item').style.opacity="0";  for(var i = 0, l = elements.length; i < l; i++){	elements[i].style.opacity = "0";  };};</script>

Looping and collections of data are pretty much the building blocks of computer programming. In order to use the method getElementsByClassName, you have to realize what it's doing. That is, it returns a collection of elements (in the form of an array) with the class item. This gives you a reference to every single one of these elements, which you can index through numerically. With this, you can use a loop, to access each element in the collection sequentially and automatically, to apply the properties to all of them. This is about as basic and simple as it gets.
Link to comment
Share on other sites

Oh, so all i have to do is draw a chart detailing every element in my site and then count the placement of each one and assign it a number? That sounds alot easier than just having it select what class i want like it does with ids. Programmers must be masters of design and simplicity.
Umm, no? Now I'm confused. Do you know what array's are?http://www.w3schools.com/js/js_obj_array.asp
Link to comment
Share on other sites

Oh, so all i have to do is draw a chart detailing every element in my site and then count the placement of each one and assign it a number? That sounds alot easier than just having it select what class i want like it does with ids. Programmers must be masters of design and simplicity.
Where are you getting that from? This is the idea, it's not very difficult:1. use a method like getElementsByClassName to get a list of elements2. loop through the list of elements3. for each element in the list, do whatever you want to itNotice that counting placement and assigning numbers is not part of that list. You get a list, and loop through it. This line gets your list:
var elements = document.getElementsByClassName('item');

Now the variable elements is a list of elements returned by the method. This code loops through the list and applies a CSS property to each element:

for(var i = 0; i < elements.length; i++){  elements[i].style.opacity = "0";}

Draw a chart? Seriously?

Link to comment
Share on other sites

I tried getting a straight answer before on here but was given a bunch of gibberish about looping and lists. Its a very straightforward request so hopefully someone can give a straightforward answer.First off im not going to tell you what im trying to do, every thread someone asks me and the whole thing gets sidetracked on how to optimize my code. The problem im having is that the geniuses who designed css decided to arbitrarily restrict the use of ID's to one per element per page. I'd use classes but apparently you cant just say getelementsbyclass ("thisistheclassiwantgoddammit") because that would be too simple. So i need to know if there is any other way to assign a 2nd set of CSS values to an ID where i can call it using a getelementbyID, like so:<style>#ID {}#ID.subID{}</style><script>function stuff(){document.getelementbyid("ID");document.getelementbyid("ID.subID");</script><body><img src="image.jpg" onclick="stuff()" id="ID" /> //I need to have two separate css styles apply to this image</body>

Link to comment
Share on other sites

Loops are one of the three fundamental parts of control flow - the principle behind imperative programming. They allow you to repeatedly evaluate the same block of code. Lists, or collections, are a fundamental data structure that allow multiple variables to be stored and accessed together. Together, these allow you to access elements in the DOM by whatever attribute you wish. I think that was explained in the other thread, however the principles will help you solve many different problems in programming in a straightforward and logical manner. I do not understand your current question, though, as IDs can only apply to a single element. You can of course modify the style of the element that has that ID as many times as you like.There are reasons behind the decisions made by the W3C and other standards bodies, and their reasoning can usually be found in the specifications (HTML) (CSS) (note that the implementation of ID fields is part of the HTML specification, and the meaning behind them can be found more generally in the documentation for SGML... but you don't really need to worry about that).

Link to comment
Share on other sites

This gives you a reference to every single one of these elements, which you can index through numerically.
Yeah, draw a chart and assign each element a number, how the ###### else am i supposed to know which element is which number?
for(var i = 0; i < elements.length; i++){ elements.style.opacity = "0";}
You see, for a normal human being to understand what a script does, they would need to be able to read it like a sentence. This reads "for variable i equals 0, i is less than elements.length, i++ (um, right), for elements labeled i, style opacity is equal to 0". Heres a link explaining what that means in english. Really though, all im asking is to be able to select a class by name. I dont want to have to loop through anything, i dont want to have to select anything numerically, i dont really care if it applies it to all elements with that class, in fact, thats exactly why i put the class in an element so why would that option even exist. It doesnt matter what the reasoning was of some bureaucrat programmer who decided all this, the fact is theres no reason why i cant just writedocument.getelementsbyclassname("thisiswhatifckingwantsoselectitgoddammit");or<img src="asdaks.jpg" id="firstcss" id="secondcss" />Why do programming languages have to be so ###### backwards? Let me program in english, it may not be efficient but it will sure as ###### get the job done and in a fraction of the time.
Link to comment
Share on other sites

It said IDs are unique so thats why i cant use more than one ID and then on classes it said

Working with HTML, authors may use the period (.) notation as an alternative to the ~= notation when representing the class attribute. Thus, for HTML, div.value and div[class~=value] have the same meaning. The attribute value must immediately follow the "period" (.). UAs may apply selectors using the period (.) notation in XML documents if the UA has namespace specific knowledge that allows it to determine which attribute is the "class" attribute for the respective namespace. One such example of namespace specific knowledge is the prose in the specification for a particular namespace (e.g., SVG 1.1 [sVG11] describes the SVG "class" attribute and how a UA should interpret it, and similarly MathML 2.0 [MATH20] describes the MathML "class" attribute.)For example, we can assign style information to all elements with class~="pastoral" as follows:*.pastoral { color: green } /* all elements with class~=pastoral */or just.pastoral { color: green } /* all elements with class~=pastoral */The following assigns style only to H1 elements with class~="pastoral":H1.pastoral { color: green } /* H1 elements with class~=pastoral */Given these rules, the first H1 instance below would not have green text, while the second would:<H1>Not green</H1><H1 class="pastoral">Very green</H1>To match a subset of "class" values, each value must be preceded by a ".".For example, the following rule matches any P element whose "class" attribute has been assigned a list of space-separated values that includes "pastoral" and "marine": p.marine.pastoral { color: green }This rule matches when class="pastoral blue aqua marine" but does not match for class="pastoral blue".Note. CSS gives so much power to the "class" attribute, that authors could conceivably design their own "document language" based on elements with almost no associated presentation (such as DIV and SPAN in HTML) and assigning style information through the "class" attribute. Authors should avoid this practice since the structural elements of a document language often have recognized and accepted meanings and author-defined classes may not.Note: If an element has multiple class attributes, their values must be concatenated with spaces between the values before searching for the class. As of this time the working group is not aware of any manner in which this situation can be reached, however, so this behavior is explicitly non-normative in this specification.
Wow, that told me everything i wanted to know about looping through lists. Gotta love the confusopoly and the nerd superiority complex.
Link to comment
Share on other sites

Well, what don't you understand? You can of course also check the tutorials: http://w3schools.com/js/js_loop_for.asp http://w3schools.com/js/js_obj_array.asp, but as they say:

Loops execute a block of code a specified number of times, or while a specified condition is true.
The Array object is used to store multiple values in a single variable.
You can use them to access multiple elements with the same class, as demonstrated:
var elements = document.getElementsByClassName('item'); // get all elements of class name "item" in an arrayfor(var i = 0, l = elements.length; i < l; i++) { // loop through them	elements[i].style.opacity = "0"; // set their opacity to 0} // that's it! That is how you can assign a style to multiple elements of the same class

I do think your attitude is discouraging people. We are trying to aid you; do with it what you want, but I doubt people have infinite patience - and insults, swearing, do little to help the situation.As for why programming languages seem so different from "plain English" is an interesting issue, but hey, at least your not trying to program in Assembly :).

Link to comment
Share on other sites

The getElementsByClassName function returns an array. To access each element in the array you need to loop over it. That's all there is to it. There is no way around that. Unless you already know the length of the array, but that's going to be a lot of code and a lot of inefficiency.I think a better way to accomplish your goal might be to pass the element to your function using the this keyword. Ie,

<script type="text/javascript">function transition(el) {			el.style.opacity="0";}......<img src="myimage.jpg" class="item" onclick="transition(this)" />

That way your function becomes reusable. this sends a reference to the element that was clicked to the transition function, where you can do whatever you want to do with it.

Link to comment
Share on other sites

Yeah, draw a chart and assign each element a number, how the ###### else am i supposed to know which element is which number? You see, for a normal human being to understand what a script does, they would need to be able to read it like a sentence. This reads "for variable i equals 0, i is less than elements.length, i++ (um, right), for elements labeled i, style opacity is equal to 0". Heres a link explaining what that means in english. Really though, all im asking is to be able to select a class by name. I dont want to have to loop through anything, i dont want to have to select anything numerically, i dont really care if it applies it to all elements with that class, in fact, thats exactly why i put the class in an element so why would that option even exist. It doesnt matter what the reasoning was of some bureaucrat programmer who decided all this, the fact is theres no reason why i cant just writedocument.getelementsbyclassname("thisiswhatifckingwantsoselectitgoddammit");or<img src="asdaks.jpg" id="firstcss" id="secondcss" />Why do programming languages have to be so ###### backwards? Let me program in english, it may not be efficient but it will sure as ###### get the job done and in a fraction of the time.
You keep complaining about ID's and classes. If it's only one element, then just use document.getElementById() and make it so in the style sheet. Maybe because you were using getElementsByClassName, and we assumed you actually meant to use that because you would have multiple elements on the page, and that the topic of your title was "javascript won't respond to classes", but idk, maybe it's just us...... :)In the future though, what you need to do is stop being so hot-headed, step back for a minute, and chill out, and try and try and understand what people are trying to explain to you. Telling us we have nerd complexes because we can't explain something to you does little to encourage to keep helping you. You came to us with a problem, and set the foundation using getElementsByClassName and classes in the topic title, so that's the direction we thought we needed to take you down. Clearly we were wrong, but your attitude and verbage did little to make the situation any better. There are way's to make function generic and specific, by passing references to elements to a function using this, which can allow for greater reuse and flexibility to your code, which may need to be implemented in this situation, depending on what the ultimate end goal of this thread turns out to. But seriously though, get over yourself.
Link to comment
Share on other sites

I tried getting a straight answer before on here but was given a bunch of gibberish about looping and lists. Its a very straightforward request so hopefully someone can give a straightforward answer.
Here you go pal, a straightforward answer to a programming question, which doesn't require any knowledge of programming:Find someone you can hire to do your work who is either a programmer or is willing to learn. You obviously don't want to learn anything, you just think it should work like you want it to work. You expect the world to change to meet your expectations instead of you adapting and actually trying to improve yourself. With that attitude, you are perfect for a middle management position that doesn't require you to learn anything new or do any of the actual work.Hopefully that's something you can understand without requiring you to put any actual effort into anything, because I sure wouldn't want to ask you to make an effort.
Link to comment
Share on other sites

Yeah, draw a chart and assign each element a number, how the ###### else am i supposed to know which element is which number?
You are NOT supposed to know which element is which number.The document.getElementsByClassName() method, as well as any similar approach, is going to return for you a list (the term is "array", but it basically means just that - a list, a collection) of all elements matching the class name specified. Each element in this list is automatically given a corresponding number, so you don't have to do that. The first element in the document is given the number 0, the second is given the number 1 and so on.Once you get all elements you want to do something with, you don't tell to the computer "do this to all of them". Instead, you tell it "do the following to each item in this list" after which you describe "the following". Doing something repeatedly (e.g. "to each" or up to a certain point) is what's called a "loop".Just try any of the examples provided above.If you're still don't getting the fact that IE8 and below doesn't support getElementByClassName() and haven't added Deirdre's Dad code as a workaround for it, try this (works in IE8 and above, as well as all latest versions of all other browsers; Does NOT work in IE7 and below):
var elements = document.querySelectorAll('.item');/* get all elements of class name "item" in an array; same deal as above, only it works in IE8 out of the box and uses CSS selectors instead of plain class names. Therefore, yes, the "." in there is required. */for(var i = 0, l = elements.length; i < l; i++) { // loop through them	elements[i].style.opacity = "0"; // set their opacity to 0} // that's it! That is how you can assign a style to multiple elements of the same class

If you can't comprehend even that, I'll have to reiterate what justsomeguy said.

Link to comment
Share on other sites

Once you get all elements you want to do something with, you don't tell to the computer "do this to all of them". Instead, you tell it "do the following to each item in this list" after which you describe "the following".
A design flaw
I think a better way to accomplish your goal might be to pass the element to your function using the this keyword.
A workaround to this design flaw.
you are perfect for a middle management position that doesn't require you to learn anything new or do any of the actual work.
A guy who will never reach management.Thanks, seems to be all i need to know about the situation. Now if only those genius W3C people could just have said "hey, were brilliant programmers, but none of us have an ounce of design sensibility, so you'll have to write the following convoluted looping script instead of just using a keyword like the rest of the html/css/java cluster###### does, or better yet, use the .this keyword and save yourself the headache". Maybe they need a middle manager to help interpret their poorly documented gibberish...:)
Link to comment
Share on other sites

A guy who will never reach management.
Indeed. Never reach a lot of things.
convoluted looping script
Seriously. Those three lines of code are so confusing. I have no idea how millions of people worldwide, even people who don't speak English, are able to understand that confusing, confusing stuff. It's really confusing. Seriously.
Maybe they need a middle manager to help interpret their poorly documented gibberish.
I think they need you. I think you need to submit a proposal about all of the design decisions they got wrong, and specifically how they can be corrected. There are a lot of things wrong with the DOM and CSS, but looping through arrays isn't exactly one of them. Find a single programmer who doesn't use loops and other basic control structures as an integral part of any application, in any programming language.
Thanks, seems to be all i need to know about the situation.
Glad we got that settled. If you have any questions in the future, there are plenty of people around here who would appreciate some paid work. I think there's a Chilean who would love to bid on your projects.
Link to comment
Share on other sites

A design flaw
For the record, W3C has nothing to do with W3Schools and we have nothing to do with either party's staff (just in case you were thinking that). The W3C has defined all of those functions based on consensus between browser vendors.OK, let's assume all browser vendors are wrong. That this is indeed a huge design flaw. "Programming EPIC FAIL" if you will.What's your idea? How exactly would you have preffered to write this? Mind you, after your proposal, we shall throw a few use cases your way, and see if your "better" design can handle them in any way. Also keep in mind that the computer in general is really dumb, and so it can't automatically tackle ambiguities - there'll always be a need to either make something be "the default way" with "that other way(s)" describing something additional, or not make something "the default way" and always explicitly state out the "obvious" for you.
Link to comment
Share on other sites

I thought i already explained how to fix this design error. Instead of

<script type="text/javascript">function transition() {  var elements = document.getElementsByClassName('item').style.opacity="0";  for(var i = 0, l = elements.length; i < l; i++){	elements[i].style.opacity = "0";  };};</script>

this

<script type="text/javascript">function transition() {			document.getElementsByClassName('item').style.opacity="0";}</script>

Just let people write the class name they want, and by default getAllFckingElementsByThatClassName('goddammit'). They already let you write the number after it if you needed to select a particular element with that class name, why wouldnt the omission of that number constitute a select-all? ######, if there were some huge technical reason why the laws of mathematics couldnt possibly allow such a thing, it could be as simple as saying [all] or [-] or [n]. Its a select-all command for christs sake, what, are we back in 1992? Do i need to get out my floppy diskettes so i can load the dos command for select-all?

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...