...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
April 7, 2012

How to create pause or delay in FOR loop?

Question by jams

I am working on a website, where I need to create a pause or delay.
So please tell me How to create pause or delay in for loop in javascript or jQuery

This is a test example

 var s = document.getElementById("div1");
 for (i = 0; i < 10; i++) {
     s.innerHTML = s.innerHTML + i.toString();
     //create a pause of 2 seconds.
  }

Answer by jams

I tried all one, but I think this code is better one, it is very simple code.

var s = document.getElementById("div1");
var i = 0;
setInterval(function () {s.innerHTML = s.innerHTML + i.toString();  i++;}, 2000);

Answer by Starx

This is how you should do it

var i = 0;
setTimeout(function() {
   s.innerHTML = s.innerHTML + i.toString();
   i++;
},2000);
Read more

Is there an html "location" element?

Question by TestSubject528491

The HTML5 time element looks pretty cool, but I’m wondering if there’s such thing as a location or place element. It may be useful in GPS applications or the like?

Answer by Whymarrh

Sadly the <location> element doesn’t exist. I for one would agree that semantically it’d be great for web-apps that involve some sort of GPS, and can foresee the W3C adding it in the future (why not?).

But, if I understand correctly, HTML5 allows you create custom elements which may be a temporary fix for an up-and-coming web-app. Semantically I don’t think this is the greatest thing, all that extra markup to create an element, but some may use it. Eric Meyer has an article discussing custom elements.

Although, technically, I think that most browsers will render unknown markup given the proper CSS and/or JavaScript …

Answer by Starx

There is no such element called “location”.

You can show your GPS data in HTML using Google Maps API

   <div id="map" style="width: 400px; height: 300px"></div> 

   <script type="text/javascript"> 
      var myOptions = {
         zoom: 8,
         center: new google.maps.LatLng(51.49, -0.12),
         mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      var map = new google.maps.Map(document.getElementById("map"), myOptions);
   </script> 
Read more

Displaying MySQL execution time in PHP

Question by 4WebDev

I have been looking around the web for this but cannot really find a good answer. I have a small site search and I want to display the time it took the mysql query to execute (similar to Google). I’ve been trying to use microtime() but I get huge strings like 1.342524564267782e25… I just want a simple digit with two decimals following (0.15). Thanks in advanced.

Answer by Starx

Use round to fix the decimal points

$time = microtime();
echo round($time, 2);
Read more

Does the <img> tag have an "onsuccess" attribute?

Question by Shahrukh

Does the <img> tag have an "onsuccess" attribute? Like "onerror".

I am loading an image. I bind an event with JQuery, which changes image onerror.
i want to show an alert "ONERROR Image loaded successfuly" if onerror image successfully loaded. Otherwise it will show alert "ONERROR image not found".

EDIT:
onload shows alert after loading image. but didn’t tells us that "your real image is loaded" or "browser's default error image is loaded". check here…

http://jsfiddle.net/extremerose71/cHuu6/6/

Answer by Engineer

If you wrote something like:

<img id="im3" src="http://ssl.gstatic.com/gb/images/j_f11bbae8.png" />​

And also wrote:

$(window).load(function() {
   $("#im3").load( function (){
      alert('load');
   }).error( function (){
      alert('error');
   });
});

(as in jsfiddle onLoad is corresponded to $(window).load) , you will never get any alert, because $(window).load will be called after all resources is already loaded.

But if you would remove src from img:

<img id="im3"/>​ 

And then add this

$("#im3").attr('src','http://ssl.gstatic.com/gb/images/j_f11bbae8.png' )​​​​​​​​​​​​​​;

line after the load and error listeners , you will see an alert.

So the main problem was , that you were adding listeners after the image has already loaded or failed to load.

Answer by Starx

You can do this using onerror and onload event handlers

var im = document.getElementById('imageid');
im.onload = function() {
   //handler
};

im.onerror = function() {
   //handler
};
Read more

How to Remove or add 2 rows in a table

Question by Mehdi

Hello !

I want to remove the current and the yellow too when I click to the basket icon on the right.

here is a screenshot :

enter image description here

here is my html code of the two rows which I want to delete by the click :

<tr>
              <td class="bar_td" colspan=7>
                <strong>PRESTATION 2</strong>
              </td>
            </tr>
            <tr class="ligne_suppr">
              <td class="jr_td">
                <img class="jour_prest" src="img/ico/jour_presta.png" alt="" width="16" height="16" /> Mardi 24 jan 2011
                <p>ou</p>
                <img class="jour_prest" src="img/ico/jour_presta.png" alt="" width="16" height="16" /> Mercredi 25 jan 2011
              </td>
              <td class="cr_td">
                <select>
                  <option value="h9">10h30</option>
                  <option value="h10">11h30</option>
                </select>
                <select>
                  <option value="h11">10h30</option>
                  <option value="h12">11h30</option>
                </select>
              </td>
              <td class="rp_td">
                <select>
                  <option value="h13" SELECTED>2h00</option>
                  <option value="h14">3h00</option>
                </select>
              </td>
              <td class="mn_td">
                <select>
                  <option value="h15">2h00</option>
                  <option value="h16" SELECTED>6h00</option>
                </select>
              </td>
              <td class="tt_td">
                <strong>8h.</strong>
              </td>
              <td class="pttc_td">
                <strong>148 &#8364;</strong>
              </td>
              <td class="cor_td">
                <a href="#">
                  <img src="img/ico/corbeille.png" alt="" width="13" height="13" />
                </a>
              </td>
            </tr>

and the Javascript code :

<script>
          $(".ligne_suppr a").click(function(e) {
            e.preventDefault();
            ($(this).parent()).parent().remove();
          })
        </script>

But with this code I can only remove the big and the yellow One stays.

Have you any idea ?
Thank you 🙂

Answer by Vapire

$('.ligne_suppr a').click(function(e) {
  e.preventDefault();
  var parent = $(this).parent().parent();  // parent <tr> of the anchor tag
  var previous = parent.prev();        // <tr> before the parent <tr>

  parent.remove();
  previous.remove();
});

Answer by Starx

This is basically going to tough to do when you dont have a specific way to select the two rows.

Create a global javascript function to remove the elements by taking the element’s id

function deleteRows(row, yellow) {
    row = document.getElementById(row);    
    row.parentNode.removeChild(row);

    yellow = document.getElementById(yellow);
    yellow.parentNode.removeChild(yellow);
}

Using jQuery you can do something like this

$(".ligne_suppr a").click(function(e) {
    e.preventDefault();
    var toprow = $(this).closest("tr");
    toprow.prev().remove(); // remove the yellow
    toprow.remove(); // remove the row
});
Read more

PHP mail() function goes to junk @ Outlook

Question by Robinjoeh

When using the PHP mail() function, the email goes to the junk folder when I use the word “utvecklat” somewhere in my message. (it doesn’t matter where)

But when I’m sending an email from Outlook to another Outlook-account (within the same mail server) it goes to the inbox.

Therefore, I think the problem is related to the mail headers.

I’m using this PHP code:

$subject='=?UTF-8?B?'.base64_encode($subject).'?=';
$emailTo="{$toEmail}";

$boundary = md5(date('U'));

$headers = "MIME-Version: 1.0rn";
$headers .= "Content-Type: multipart/alternative;boundary={$boundary}rn";
$headers .= "From: "{$fromName}" <{$fromEmail}>rn";

$message = "This is a MIME encoded message."; 

$message .= "rnrn--" . $boundary . "rn";
$message .= "Content-type: text/html;charset=utf-8rnrn";
$message .= $message_tmp;

$message .= "rnrn--" . $boundary . "--";

mail($emailTo, $subject, $message, $headers, "-f {$fromEmail}");

The email should be in HTML format. It doesn’t matter if I use “utvecklat“, the email will go to the junk folder anyway.

So, what should I do to avoid the spam filter in Outlook? (must be something to do with my email headers, because mail from Outlook to Outlook within the same mailserver goes to the inbox.)

Thank you!

UPDATE!

Here you have a email sent from a outlook account to another. Can someone “convert” all this headers to a correct PHP mail() code? Thanks!

Return-Path: <example@domain.com>
Delivered-To: robin@example.com
Received: from localhost (localhost [127.0.0.1])
    by example.example.com (Postfix) with ESMTP id 9C67EC21B12
    for <robin@example.com>; Sat,  7 Apr 2012 17:58:14 +0200 (CEST)
X-Virus-Scanned: Debian amavisd-new at example.example.com
X-Spam-Flag: NO
X-Spam-Score: -2.47
X-Spam-Level: 
X-Spam-Status: No, score=-2.47 required=6.31 tests=[ALL_TRUSTED=-1,
    BAYES_00=-1.9, HTML_MESSAGE=0.001, MIME_HTML_MOSTLY=0.428,
    TVD_SPACE_RATIO=0.001] autolearn=ham
Received: from example.example.com ([000.000.000.00])
    by localhost (example.example.com [127.0.0.1]) (amavisd-new, port 10024)
    with ESMTP id HIlqLaU+2IIL for <robin@example.com>;
    Sat,  7 Apr 2012 17:58:11 +0200 (CEST)
Received: from Ciccidator (00-000-00-000-no56.tbcn.telia.com [00.00.00.000])
    by example.example.com (Postfix) with ESMTPA id 866F2C2059C
    for <robin@example.com>; Sat,  7 Apr 2012 17:58:11 +0200 (CEST)
From: "Example Sender" <example@domain.com>
To: <robin@example.com>
Subject: utvecklat
Date: Sat, 7 Apr 2012 17:58:01 +0200
Message-ID: <000001cd14d7$35d38070$a17a8150$@example.com>
MIME-Version: 1.0
Content-Type: multipart/alternative;
    boundary="----=_NextPart_000_0001_01CD14E7.F95C9E90"
X-Mailer: Microsoft Outlook 14.0
Thread-Index: Ac0U1zWPte9QsazETMuTKG6LDnf1fg==
Content-Language: sv

Answer by Starx

Omitting the junk mail covers a lot of ground, and can never be a 100% solution. Because email filtration might be different from one span engine to other.

  • One the best way to confirm you always receive the mail is to the add the sender’s email address on the recipient’s address book.

  • Another, you should confirm if the sender’s email is not blacklisted on the internet.

  • Always confirm you have sent the emails with correct header.

  • Use Email Libraries like PHP Mailer

Fruther more: Check out this answer about MX entries.

Read more

Error message not get cleared while clicking the reset button

Question by vivek

I am using jquery.validate.js file to validate an input form, It works fine, my problem is the error messages are not get cleared while clicking the reset button in the form.

how to get clear the form?

here is the code

 <script type="text/javascript" src="js/jquery.js"></script>

 <script type="text/javascript" src="js/jquery.validate.js"></script>


  javascript function

      $(document).ready(function(){        

        $("#demo-form").validate({    
          rules: {
            name: "required",
            address: "required",
       }

HTML Code

<div><input type="text" id="name" name="name" /></div>

<div><input type="text" id="address" name="address" /></div>

<div> <input type="submit" id="submit" value="Validate!" />
      <input type="reset" id="reset" value="Reset" />   

Answer by Starx

Basically, when you click the reset button. It will be responsible for clearing the fields, not the label. Normally, jquery validate plugin, keeps its validation messages in labels. So in order to clear them, use

$('label.error').remove();

call this on the click of reset button
where it is needed.

Read more

Show/hide div on page scroll

Question by santa

I have a table with a lot of rows, which makes the page scroll. There’s some other content above the table. I would like to add a functionality using jQuery, to show div across the page top, as soon as the table scrolls to the point, where the top row disappears above the top border of the screen.

I assume I’ll add a div with position set to fixed, but how do I know when the top row moves above the fold?

<div id="topDiv" style="display: none; position: fixed; top: 0"></div>

<table>
<thead>
<tr>
   <th></th>
<tr>
</thead>
<tbody>
<tr>
   <td></td>
<tr>
...
</tbody>
</table>

Answer by ckaufman

Answer by Starx

You can use something like this

$(window).scroll(function(e){ 
  $el = $('#topDiv'); 
  if ($(this).scrollTop() > 200 && $el.css('position') != 'fixed'){ 
    $el.css({'position': 'fixed', 'top': '0px'}); 
  } 
});

This check if the window has scrolled above 200px and fixes the topDiv

Read more

Change date Format in jQuery DatePicker to English dd/mm/yy?

Question by MickySmig

I’m trying to format the date of a jQuery DatePicker to the English format ‘dd-mm-yy’, but I’m unable to get it to work. I’ve looked at all of the answers on this site and they all are using the same code as I am. Any idea why mine is not working? I have tried the two following ways:

$(function () {
    $(".datefield").datepicker({dateFormat:'dd/mm/yy'});
});

$(function () {
    $(".datefield").datepicker({ dateFormat: 'dd-mm-yy' });
});

Neither of these have worked. I was wondering if I had to include some other jQuery file to get the date to format to English.

Any help, as always, is greatly appreciated.

Answer by Starx

If you are trying to change it, use the setter method

$( ".datefield" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );
Read more

Is it possible ? "Javascript Subclass"

Question by EyeSalut

I want to know i can do something “similar” to this (not working) code in javascript ?

function Player ()     {

    this.Inventory = function ()     {

        this.Inventory.UseItem = function(item_id)    {
            /* use the item ... */
        }

    }

}

and then use it like that :

current_player = new Player();
current_player.Inventory.UseItem(4);

Answer by Starx

Yeah

function Player ()     {

    var Inventory = {


        UseItem : function(item_id)    {
            /* use the item ... */
        }

    };

}
Read more
...

Please fill the form - I will response as fast as I can!