As my first jQuery project, I’m trying to write a “stoplight” status indicator that cycles through “off”, “green”, “yellow”, and “red” circle images and POSTs the information so I can record it in a DB. I’m currently trying to use the toggle() function, and it works except that I have no way to “initialize” the value to the preexisting database state.
Here’s what I have:
$('.stoplight').toggle(
function () {
$.post('post.aspx', { recordid: <%= this.Id %>, lightid: this.id, value: 'yellow' });
$(this).attr('src', '/Images/Stoplights/yellowStatus.gif');
},
function () {
$.post('post.aspx', { recordid: <%= this.Id %>, lightid: this.id, value: 'red' });
$(this).attr('src', '/Images/Stoplights/redStatus.gif');
},
// ... and so forth for "off" and "green" settings
So – how do I set up the starting state of the toggle somehow during page load, or alternatively, is there another method by which I could implement this better?
Here’s an alternative way of toggling through the various lights. I used divs instead of images, but the principle is the same. See it in action here: http://jsfiddle.net/vy7wX/3/
In your case you can do two things: either check the current image src and retrieve the stoplight name or add a class to the image, so you can retrieve the name directly. The latter is probably easier.
Example:
And the JS for changing the image src and posting the status:
Using this it doesn’t matter what the start position of the light is, and you can simple add the correct class as starting position depending on the current status in the database.
Edit
As for jQuery 1.3.2. The documentation states that the
.toggleClassmethod was added in 1.3 and it can toggle multiple classes at the same time. Elsewhere online I find that 1.3 can only handle one class though, so I assume the method itself was added in 1.3 but it got extended functionality in 1.4 which wasn’t documented on that page.Anyways, it’s no problem. Like you said, you can simply toggle the two classes separately. But if you need to use the method twice you might use
removeClassandaddClassinstead so the script reads better. I also forgot the class update in the last part, so the end will be something like this:Also, to cut back on lines of code the
position_newvariable can be defined as this: