Question

I am using this code to toggle visibility

var prevId;

function toggle_visibility(id) {
   if(prevId){
      $("#"+prevId).slideToggle("slow");
   }
   var e = document.getElementById(id);

      $(e).slideToggle("slow");
   prevId = id;

}

On the div that appears I am using this to display the data from the database

<?php 
include"scripts/connect_to_mysql.php";
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET 'utf8'");

$news="";
$sql=mysql_query("SELECT *
FROM `news` 
ORDER BY date DESC"); 
$newsCount=mysql_num_rows($sql);
if ($newsCount>0) {
    while($row=mysql_fetch_array($sql)){
        $id=$row["id"];
        $title=$row["title"];
        $text=$row["text"];
        $date=$row["date"];
        $news.=' <table width="800" border="0">
  <tr>
    <td style="width:150px;">' . $date . '</td>
    <td style="width:600px; overflow:hidden;"><a href="?id=' . $id . '#" onclick="toggle_visibility(\'news_det\');" style="color:#b19057;" >' . $title . '</a></td>
    <td style="width:50px"><a href="#" onclick="toggle_visibility(\'news_det\');" style="color:#000;">...more</a></td>
  </tr>
</table>
';
    }

}else {
    $news="No news available yet";
}

?>

The problem is that if i click on this link

<a href="?id=' . $id . '#" onclick="toggle_visibility(\'news_det\');" style="color:#b19057;" >' . $title . '</a>

the toggle starts but interrupts on the first click, but works on the second.

Any ideas on what I am doing wrong?

Was it helpful?

Solution

I have two recommendation for your code to solve your problem

One Way

Change your JavaScript function to something like this

var prevId;

function toggle_visibility(id, newsId) {
    if (prevId) {
        $("#"+prevId).slideToggle("slow");
    }
    $("#"+id).slideToggle("slow");
    if (id=="news_det" && newsId!=undefined) {
        var val=$("#det_"+newsId).val();
        $('#news_detDiv').html(val);//Where you are putting text that div id
    }
    prevId = id;
    return false;
}

Change your html snippet from $news variable to this

$news.='<table width="800" border="0">
    <tr>
        <td style="width:150px;">' . $date . '</td>
        <td style="width:600px; overflow:hidden;"><a href="#" onclick="toggle_visibility(\'news_det\', '.$id.');" style="color:#b19057;">' . $title . '</a></td>
        <td style="width:50px"><a href="#" onclick="toggle_visibility(\'news_det\', '.$id.');" style="color:#000;">...more</a></td>
        <input type="hidden" value="'.$text.'" id="det_'.$id.'">
    </tr>
</table>';

In this way you will save your server call, since you will be storing all your text in your page only and you will always see relevant post data on click of title & more. Moreover your effect will also work.

Second Way

You should use JQuery AJAX call on click of title & more to get data from server instead of going with refreshing page.

Happy Coding!!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top