I asked a similar question here where I wanted to get a single div to show/hide rather than all the divs. This was solved and I used one of the answers provided. However further down the line I ran into some problems where it would open the wrong corresponding div and it was suggested that I use ID’s to open the correct corresponding div. The divs are dynamically generated along with their ID’s and they are matching as expected.
My problem is that the jQuery script doesn’t work any more (i’ve rewritten it using advice from other answers in the previous question) – does anyone know what the problem is?
A quick look at the javascript console (F12) showed the following error message:
This error is raised because you are trying to use the variable
$indexoutside of the scope it is defined (within the click handler).Here is a working modified version with the following alterations:
within an event handler, using
this.idis sufficient to get the ID of an element asthisin an event handler is a DOMElement and not a jquery objectuse .replace() or .substring() to get the last two digits of the id. .charAt() only returns 1 character at the specified position
the ID selector in jquery is
#<id>–>"#slidingDiv" + idxonly prefix the jquery variables with
$, not regular variables. it is just a convention but when you see$myvariableyou then expect it to be a jquery objectDEMO