call the jquery onclick function


Probably beginner jquery question... Here is my problem:

I have dynamically created list of div elements. Each has its' specific content, id and a toggle icon in the corner. When I press toggle icon it causes the following: expands/hides the content of the div and changes the icon.

My initial thinking was to call 2 custom jquery functions something like this (the number is dynamically inserted by PHP):

<div id="div152" >
  <div id="content152">some content</div>
  <a id="toggle-icon152" href="javascript:void(0);" onclick="togglemydiv(content152); changeicon(icon152)">
    <div id="icon152">someicon</div>

Now this works in some browsers but obviously it is not how it should be done as it doesn't work in FF in windows or in fiddle. Any help would be appreciated.

I suggest that you don't hardcode your ids into js.

Here is a suggestion how to do it simpler:


<div id="div152" >
  <div id="content152">some content</div>
  <a id="toggle-icon152" data-bind-action="toggle-content" href="#">
    <div id="icon152">someicon</div>



function toggleContent(){
    var a = $(this);
    var div = a.prev();
    return false;

Se how it works on jsfiddle.

Here is version which does not assume your content is prev element to a, but you add attribute to your link so it knows what to toggle:

I have added html5 data- attribute to identify anchor to which toggle function needs to be attached from js, you can do this different, of course, using class or other (faster?) jQuery selector.

As @coosal said in its answer, if divs are dynamically generated (ajax or on client), you need to use live instead of binding on document.ready, so here is version which uses live: