Jump to content

Decoding this Javascript Function


zeroblitzt

Recommended Posts

Hello friends,

 

 

I do not consider myself a thief. That is why I wouldnt outright steal this code. But I am trying to at least understand it, for you see, I am very, very new to Javascript. I hope that I could then write my own function of a similar nature.

 

Anyway, the code in question:

function toggle_spoiler(obj) {
  while (!/spoiler_(?:open|close)/.test(obj.className))
    obj=obj.parentNode;
  obj.className=obj.className.indexOf('closed') != -1 ? obj.className.replace('closed', 'opened') : obj.className.replace('opened', 'closed');
  return false;
}

 

This is what it does:

 

1. On a page, there would be 4 <span> tags, which call the following CSS classes:

.spoiler_on_close
.spoiler_close
.spoiler_open
.spoiler_on_open

Oddly enough, they all do the same thing: 

display: none;

 

 

2. Inside the spans, there are two hyperlinks that call the "toggle_spoiler" function listed above. Basically, the function hides text, hence the name "spoiler" -- it can be used to hide sensitive parts of movies, video games, etc. that shouldn't be revealed without ruining the whole thing for someone else. To activate this spoiler, a user would type "<spoiler>" and to close it would be "</spoiler>" -- sort of a pseudo HTML tag. this sandwiches any text in between, which becomes hidden.

 

3. So when someone clicks the first hyperlink (accurately marked "spoiler"), it unhides the text on the inside by calling the toggle_spoiler function. Then, a user could click either the original <spoiler> tag, or the </spoiler> tag (which was unhidden with the rest of the text), and that would end up closing/rehiding the text.

 

 

Hope that wasn't too confusing.

 

Anyway, the Javascript aspect of it is the only part I cant figure out, and rightly so,  because its basically the entire operation. If anyone could help me break this down bit by bit I'd greatly appreciate it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.