Jump to content

can you write javascript that produces functioning javascript?


dadamssg87

Recommended Posts

can you write javascript that produces/writes/etc. functioning javascript?

 

for example, have a link that has a function tied to it that when clicked produces a functioning javascipt snippet? The snippet could deal with a completely other elements.

 

For example

 

Link #1(has the javascript function that produces javascript)      Link #2(does absolutely nothing for now)

 

Click on link #1(produces javascript snipped that says "when link #2 is clicked document.write('hello')"

 

Clicking on link #2 now produces "hello" whereas it previously did nothing. Is that possible?

 

Link to comment
Share on other sites

That's called binding events. You would pre-define the code so that when the click event is triggered on Link#1, you bind the event to Link#2:

 

<script type="text/javascript">
window.onload = function() {
    var link1 = document.getElementById('link1');
    // Bind the onclick event to link1
    link1.onclick = function() {
        var link2 = document.getElementById('link2');
        // Bind the onclick event to link2
        link2.onclick = function() {
            alert('Hello');
            return false;
        }
        return false;
    }
}
</script>

<a id="link1" href="#link1">Link 1</a>
<a id="link2" href="#link2">Link 2</a>

 

I'm using function expressions here (the unnamed functions) as you're unlikely to re-use the code. If you did you might want to consider adding the code to a separate, named/declared function, and setting the onclick event to just call that:

 

link1.onclick = nameOfFunctionHere;

 

Also I added the return false statements so that the normal default action of the link is ignored. You might want to remove those though..?

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.