dadamssg87 Posted May 22, 2011 Share Posted May 22, 2011 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? Quote Link to comment https://forums.phpfreaks.com/topic/237157-can-you-write-javascript-that-produces-functioning-javascript/ Share on other sites More sharing options...
RichardRotterdam Posted May 23, 2011 Share Posted May 23, 2011 Can't you simply change what happens in the onclick events by setting some variables? Quote Link to comment https://forums.phpfreaks.com/topic/237157-can-you-write-javascript-that-produces-functioning-javascript/#findComment-1218993 Share on other sites More sharing options...
Adam Posted May 23, 2011 Share Posted May 23, 2011 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..? Quote Link to comment https://forums.phpfreaks.com/topic/237157-can-you-write-javascript-that-produces-functioning-javascript/#findComment-1219001 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.