Category Archives: JQuery

setInterval or setTimeout

setInterval

<!DOCTYPE html>
<html>
	<head>
		<title>Jquery setinterval stop after sometime</title>
		<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
		<script type='text/javascript'>
			$.ajaxSetup({ cache: false })
		</script>
	</head>
	<body>
		<input type="button" value="Start count!" onclick="startTimer()"> 
		<input type="button" value="Stop count!" onclick="stopTimer()"> 
		<br/>
		<div id="countdown_text">Placeholding text</div>
		<script type="text/javascript">
			var timer = null, 
			value = 0;

			function startTimer(){
				if (timer !== null) return;
				timer = setInterval(function () {
					document.getElementById('countdown_text').innerHTML = ++value;
				}, 1000); 
			}

			function stopTimer(){
				clearInterval(timer);
				timer = null
			}		
		</script>
	</body>
</html>

setTimeout

<!DOCTYPE html>
<html>
<body>
	<title>Jquery setinterval stop after sometime</title>
		<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
		<script type='text/javascript'>
			$.ajaxSetup({ cache: false })
		</script>
		<button onclick="startCount()">start</button>
		<button onclick="stopCount()">stop</button>
		<div id="countdown_text">Placeholding text</div>

		<script>
			var c = 0;
			var t;
			var timer_is_on = 0;

			function timedCount() {
				document.getElementById('countdown_text').innerHTML = c;
				c = c + 1;
				t = setTimeout(
						function(){ 
							timedCount() 
						}, 1000
					);
			}

			function startCount() {
				if (!timer_is_on) {
					timer_is_on = 1;
					timedCount();
				}
			}

			function stopCount() {
				clearTimeout(t);
				timer_is_on = 0;
			}
		</script>
</body>
</html>

Remark :
setTimeout (無限loop)
setTimeout (僅行一次)

Loading Page in JQuery

index.php

<script src="loading.js" type="text/javascript"></script>
<link media="screen" rel="stylesheet" type="text/css" href="slyte.css" />

<div id='loading' style='display: none;'>
     Loading...
</div>

<a onclick="activate_ajax_loading('content_1.html')" href="#content_1">content_1</a> |
<a onclick="activate_ajax_loading('content_2.html')" href="#content_2">content_2</a>

slyte.css

<style>
#container { line-height: 20px; width: 500px; height: 500px; margin: 20px 0; padding: 10px; border: 1px solid #999; }
// Loding Color is Blue
#loading { MARGIN-LEFT: 90%; position: absolute; top: 0; left: 0; color: white; background-color: blue; padding: 5px 10px; font: 12px Arial; }
// Loading Color is red
#loading { position: absolute; top: 0; left: 0; color: white; background-color: red; padding: 5px 10px; font: 12px Arial; }
</style>

Loading.js

<script type='text/javascript'>
activate_ajax_loading = function(url) {
   $('#loading').ajaxStart(function(){
       $(this).fadeIn();
   }).ajaxStop(function(){
       $(this).fadeOut();
   });
   $("#content").load(url);
}
</script>

<strong>content_1.html</strong>
<pre class="brush:php">content1.html</pre>
<strong>content_2.html</strong>
<pre class="brush:php">content2.html</pre>

Auto Load More Data On Page Scroll in PHP

index.php

<?php
    $items_per_group = 10;
    $result = mysql_query("SELECT COUNT(*) as t_records FROM uhouse");
    $row = mysql_fetch_array($result);
    $t_records = $row['t_records'];
    $total_groups = ceil($t_records / $items_per_group );
?>

<script type="text/javascript" language="javascript">
// <![CDATA[
    $(document).on('pageinit', '#index' ,function(){
        var track_load = 0;
        var loading  = false;
        var total_groups = <?php echo $total_groups; ?>;

        $('#results').load("do-index.php", {
          'group_no':track_load}, function() {
           track_load++;
        }); //load first group
        
        $(window).scroll(function() {
        if($(window).scrollTop() + $(window).height() == $(document).height()){
        if(track_load <= total_groups && loading==false){
            oading = true;
                $('.loading_image').show();
            $.post('getData.php',{'group_no': track_load}, function(data){
            $("#results").append(data).trigger("create");
            $('.loading_image').hide();
                        track_load++;
            loading = false;
                }).fail(function(xhr, ajaxOptions, thrownError) {
            alert(thrownError);
            $('.loading_image').hide();
            loading = false;
            });
        }
       }
    });
});
// ]]></script>

<span id="results"></span>
<div class="loading_image" style="display:none" align="center">
    <img src="loading_icon.gif">
</div>

do-index.php

<?php
if($_POST){
    $items_per_group = 10;
    $group_number = filter_var($_POST["group_no"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
    $position = ($group_number * $items_per_group);

    //throw HTTP error if group number is not valid
    if(!is_numeric($group_number)){
        header('HTTP/1.1 500 Invalid number!');
        exit();
    }

    $haunted  = array();
    $query = mysql_query("SELECT * FROM  `uhouse` order by id DESC LIMIT $position, $items_per_group");
    while ($rows = mysql_fetch_array($query, MYSQL_ASSOC)) {
         $haunted[] = $rows;
    }

    echo "<ul data-role='listview' data-inset='false' data-scroll='y'>";
    foreach($haunted as $key=> $h){
        echo "<li>";
        echo "<h2>".$h['id']." ".$h['date']." ( ".$h['area']." ) </h2>";
        echo "<h2>".$h['address']."</h2>";
        echo "<p style='white-space:normal;'>".$h['cause']."</p>";
        echo "</li>";
    }
    echo "</ul>";
}
?>

CREATE TABLE IF NOT EXISTS `uhouse` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `area` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `address` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `cause` text COLLATE utf8_unicode_ci NOT NULL,
  `map_point` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `area` (`area`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;