Jump to content

Dynamic onClick


javascriptdork

Recommended Posts

Not sure exactly what you mean, but I'll go by what I think you mean...

 

When you create the <div> that needs the clickable effect, give the div an id.  Then either document.getElementById or a jQuery selector will get you that element to attach the clickable event to. 

 

Personally,I'm a big fan of jQuery:

//create the div
$('<div id="clickableDiv">Content of Div here</div>').appendTo('#originalDiv');
$('#clickableDiv').click(function(){
     your onClick action goes here
     ...
};

This assumes the containing div has id=originalDiv and the dynamically created div gets the id "clickableDiv" as shown in the code.

 

In jQuery appendTo will put it at the end of originalDiv; alternately you can use prependTo() to put it at the beginning and push everything else down or to the side (depending on your css).  If the div is empty, it doesn't matter which one you use, really.

 

If an entire array is creating the clicable divs, you can dynamically create id's using the index pointer during the foreach (or .each() if you're using jQuery)

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.