News:

SMF 2.1.4 has been released! Take it for a spin! Read more.

Main Menu

Adding JS bits within index.template.php

Started by BGH, June 28, 2012, 02:29:42 PM

Previous topic - Next topic

BGH

Hello,

I have a very tiny JS file:


$(document).ready(function()
{
  $('.blabla').hide();
  $('.blabla_head').click(function()
  {
    $(this).next('.blabla_body').slideToggle(100);
  });
});


And I'm "calling" it through index.template.php, like this:


<script type="text/javascript" src="', $settings['default_theme_url'], '/scripts/blabla.js"></script>


But I realize that this can be avoided, in favor of a much better and efficient performance, by adding the JS code inside the index.template.php template. I tried adding it with echo ' and ending it with '; like this:


echo '
<script type="text/javascript"><!-- // --><![CDATA[
$(document).ready(function()
{
  $('.blabla').hide();
  $('.blabla_head').click(function(),
  {
    $(this).next('.blabla_body').slideToggle(100);
  });
});
// ]]></script>';


But it didn't work, 'cos it throws error. So I wanted to know the correct way to achieve this.

Could someone help me to do this?

Thanks in advance!

Arantor

That code requires jQuery, which is not included by default, add another <script> line to load jQuery first before calling your code.

BGH

Thanks for the fast response, Arantor.


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>';
echo '
<script type="text/javascript"><!-- // --><![CDATA[
$(document).ready(function()
{
  $('.blabla').hide();
  $('.blabla_head').click(function()
  {
    $(this).next('.blabla_body').slideToggle(100);
  });
});
// ]]></script>';


So, is that ok?

I tried it but still shows error. I think I'm missing something else...

Shambles

I'm also trying to learn this stuff, and I think you might need to escape those apostrophes as they're within the echo string ...

{
  $(\'.blabla\').hide();
  $(\'.blabla_head\').click(function()
  {
    $(this).next(\'.blabla_body\').slideToggle(100);
  });
}


Could be wrong tho

BGH

We are getting closer, thanks Shambles™

Now it doesn't shows errors, though the JS code doesn't seem to work properly.

It's a button that should show some content by clicking it, but doing that doesn't show anything at all.


EDIT: Argh, silly me!! I was using '/' instead of '\', so that explains why it didn't work in the first place. Now it does fairly well! So then, the code should be:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>';
echo '
<script type="text/javascript"><!-- // --><![CDATA[
$(document).ready(function()
{
  $(\'.blabla\').hide();
  $(\'.blabla_head\').click(function()
  {
    $(this).next(\'.blabla_body\').slideToggle(100);
  });
});
// ]]></script>';


Problem solved, thank you both!! :)

Advertisement: