I've been working with jQuery for a while now, I used it in multiple places around my website. But in each case, I either adapted a pre-made free script, or look at a tutorial and copied it, editing by trial and error to achieve the desired effect. I don't actually Know Javascript, or how jQuery works.
I am attempting to rectify this situation. Turns out there are quite a few free textbooks on the subject, on Javascript in general and on jQuery. The jQuery website itself has quite a bit of interesting reading as well, and I went through a few of their tutorials.
From what I've gotten, the basic idea of JavaScript is, when the use interacts with a webpage, find the element in question, and do something to it. jQuery is just a library of functions, already written out in JavaScript. You link to it, and then can call the pre-made functions, without having to write them all out. One such function that I think will be very useful, hasClass. Using it, you can get a true false reading on whether an element has a certain class, say a link that gets clicked on. Only if the value is true, will you change it. I decided to test this out, along with the follow ups, addClass, and removeClass.
First I created the html document. In the head, I used the script tag to link to jQuery and then to myscript. I also used inline css to remove the outlines from links, and to see a class of c1, as bold. In the body, I created a link, giving it by default the bold class, c1.
Next I had to write the javascript to change it back and forth. I started with a ready function, which I still don't really understand the need for, except that if it's not there, the script must be placed after the link in question, in the html document, rather than in the head.
Inside this, I used a click event. Events are times that the user interacts with our webpage. As to what is click, that is any a at all, so any link in the webpage. I could specify this, but since webpage consists of a single link, it's unnecessary. Inside that click event, I have a couple things. Reactions to the click, basically, cause and effect. First, I prevent the link from doing it's default behavior (taking us to a new page), with the even.preventDefault(). Next, I have an if/else statement, which basically checks if the class is c1 or not. If it is, then I use removeClass, to remove c1, from (this). I could set it to remove something else, but (this) is a quick way to mean the element that is already being examined. Then if the link does NOT have c1, add it.
The effect achieved it that a link starts bold on page load, and when clicked, becomes unbolded. When clicked again, bold is restored ... back and forth. Useless in its own right, but certainly an interesting experiment.
Tuesday, May 24, 2011
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment