Home > Software engineering >  Unable to make collapsible work on webpage
Unable to make collapsible work on webpage

Time:10-16

I'm attempting to made a collapsible (and hopefully simple) DIV and was working with another answer I had found here on stack overflow but I cannot seem to get it to work on my website. I do have a fiddle with the full links and coding which shows that its actually working (in the fiddle) but then I input the code into my page and it hides the stuff beneath the first picture (using that as the divider) but when I click on it nothing happens (it doesn't display)

Below is the snippet of HTML coding:

<p class="expand-one"><a href="#"></a> <img src="https://www.mywebsite.net/something/vip1.png"></p>
<p class="content-one">
<td width="33%" align="center" valign="top">
<br>
</td>
<td width="33%" align="center" valign="top">
<a href="http://www.mywebsite.net/bigslice" title="The Big Slice: Home of the Edge">
<font color="#dace77">[ m u s i c ]</font>
</a><br>
<font color="#FAF9B6">$ROOMNAME bigslice$</font><br>$USERLIST bigslice$<br>
</td>
</tr>
</p>

and up in my CSS I have the simple addition of:

<style>p.content-one {
display: none;
}
</style>

And down before the body ends where all my JS scripts are I have

<script>
$('.expand-one').click(function() {
 $('.content-one').slideToggle('slow');
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

CodePudding user response:

Since the answer was as simple as jQuery not loading before the code using it, I thought I'd post the troubleshooting steps I suggested as an answer. The question may be marked as a duplicate, but if not, maybe someone will stumble upon it and be helped... idk.

  1. Ensure any code using jQuery is added after the jQuery library is included (typically I include jQuery at the end of the body and any custom script after that, but that's personal preference).
  2. Check the brower console (F12) for errors- typically these are easy to grok, or you can search for the error message.
  3. If jQuery attempts to select an element before the element is added (either because the jQuery comes before the HTML code, or because the HTML code is dynamically added after loading), it won't find an element- thus adding a listener won't do anything. Either ensure the code comes after the element, attach the listener to a parent/ancestor and specify which element to listen for (e.g. $(document).on('click', 'p', function() { /*...*/ }) will attach a listener to the entire document which will only run when a paragraph is clicked), or use $(function() { /* code here */ }) to ensure your code doesn't run until the page is done loading.
  4. console.log() is extremely helpful if you're not sure if code just won't run, or if it's running and just not affecting anything. If nothing logs, the code isn't running.
  • Related