...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
September 9, 2013

Jquery delay background animation not working

GEspinha’s Question:

I don’t understand why this doesn’t work:

$('#myDiv').css('background', 'url("Img/image.gif")').delay(500).css('background', 'none');

I want #myDiv to have a background and it be removed after 500ms.

Can anyone help on this please?

css is not an animation, therefore delay does not affect it.

Use setTimeout instead:

var $div = $('#myDiv').css('background', 'url("Img/image.gif")');

setTimeout(function(){
    $div.css('background', 'none');
}, 500);

That is because delay() works with animations and also we cannot animate between bitmap data like images try using fadeIn() and fadeOut() instead to create the fading background effect.

Read more

Only one if/else statement executing

Clarisse’s Question:

I have two if/else statements comparing the same variable, with in one function. I do not desire, nor see a reason to nest the statements.

function checkUser() {
  var user = document.getElementById('usern').value;
  var element = document.getElementById('labelUser');

  if (user.length < 3 || user.length > 15) {
    element.innerHTML = "Invalid length.";
    element.style.color = "red";

  } 
  else {
    element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';  
  }   

  if (user.match(/[<>!@#$%^&*,]+/i)){ 
    element.innerHTML = "Invalid characters.";
    element.style.color = "red";

  }   
  else {
    element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';  
  }     

}

How could this code be improved?

function checkUser() {
  var user = document.getElementById('usern').value;
  var element = document.getElementById('labelUser');

  if (user.length < 3 || user.length > 15) {
    element.innerHTML = "Invalid length.";
    element.style.color = "red";

  } 
  else if (user.match(/[<>!@#$%^&*,]+/i)){ 
    element.innerHTML = "Invalid characters.";
    element.style.color = "red";

  }   
  else {
    element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';  
  }     
}

You can minimize the code like this:

  var gotoElse = false;
  if (user.length < 3 || user.length > 15) {
    element.innerHTML = "Invalid length.";
    element.style.color = "red";

  } 
  else gotoElse = true; 

  if (user.match(/[<>!@#$%^&*,]+/i)){ 
    element.innerHTML = "Invalid characters.";
    element.style.color = "red";

  }   
  else gotoElse = true;

  if(gotoElse) {
    element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';  
  }     
Read more

How to Get Parameters from Database in PHP with PDO

M4g4bu’s Question:

I’m developing a setup class to manage some parameters stored in the database and I am trying to make a class effective and shorter so, I did this:

First, I add a db.php file where the database is configured and connected, after that I added the parameters as private attributes. To process them in a better way all are included into an Array, so I build the query in the variable ‘consulta’ processing the information and retrieve one by one the values from the db

<?php
  require 'db.php';

  class setup {
private $lenguaje;
private $charset;
private $sitio_titulo;
private $sitio_descripcion;
private $kewords;
private $autor;
private $path_css_frontend;
private $path_css_backend;
private $path_modernizr;
private $path_jquery;
private $logo_url;
private $copyright;
private $dbconn;
private $site_version;

//edit – code separated only for visibility, part of same class

    public function __construct() {
    $this->dbconn = new database ();
}
private function fillData() {
    $valores = array (
            lenguaje,
            charset,
            sitio_titulo,
            sitio_descripcion,
            kewords,
            autor,
            path_css_frontend,
            path_css_backend,
            path_modernizr,
            path_jquery,
            logo_url,
            copyright,
            dbconn,
            site_version
    );
    $this->getData($valores);
}

//edit – code separated only for visibility, part of same class

public function getData($columnName) {

    while($columnName){

        $consulta = 'SELECT $columnName from config LIMIT 1';

        $this->dbconn->query ( $consulta );

        $this->dbconn->execute ();

        $r = $this->dbconn->fetch (); //

        '$this->'.$columnName = $r;

    }

   }

    ?>

did I something wrong?

First quote the values of your array or they will be considered as constants.

$valores = array (
            'lenguaje',
            'charset',
            'sitio_titulo',
            'sitio_descripcion',
            'kewords',
            'autor',
            'path_css_frontend',
            'path_css_backend',
            'path_modernizr',
            'path_jquery',
            'logo_url',
            'copyright',
            'dbconn',
            'site_version'
    );

Next, the way you are using while loop is wrong. Combine the array values and send one query.

public function getData($columnName) {

    $columnName = implode(",", $columnName);
    $consulta = 'SELECT $columnName from config LIMIT 1';

    // Query Now

}
Read more
September 8, 2013

Session doesn't work

User2758781’s Question:

I’m trying to make a login page. when i try to register the username as a session it should redirect me to another page, where it checks if that session is not registered. if it isn’t, it redirects me back to the login page. well, i think it fails on the second page.

Login.php:

if($count==1){$_SESSION['user'] = $username;$_SESSION['pass'] = $password;header("location:Login_Success.php");}
else{echo "<p style='color:red'>Wrong username or password!</p>";}

login_success.php:

session_start();
if(!isset($_SESSION['username'], $_SESSION['password'])){
header("location:login.php");}

You are missing session_start(); on the begining of your code.

session_start(); //This will get you connected with your previous session

if($count==1){$_SESSION['user'] = $username;$_SESSION['pass'] = $password;header("location:Login_Success.php");}
else{echo "<p style='color:red'>Wrong username or password!</p>";}
Read more

multiple selector to include back $(this)?

Merralee Mandel’s Question:

I’m not sure is this possible. Selecting multiple element is easy, but today I doubt whether this is possible or not:

$(this).closest("li, + $(this)").css('text-decoration','line-through');

The above code surely not working. It’s just for the demo of the idea. I want to strike the entire li (text and the checkbox) so I selected the li together with the checkbox.

$(this).closest("li").andSelf().css('text-decoration','line-through');

or

$(this).closest("li").addBack().css('text-decoration','line-through');

for jQuery 1.8 and above

You can use .add() function to add selectors:

$(this).closest("li").add(this).css('text-decoration','line-through');
Read more

extract info from another web page

Catalin Preda’s Question:

I have this test.php where i have this info :

callername1 : 'Fernando Verdasco1'
callername2 : 'Fernando Verdasco2'
callername3 : 'Fernando Verdasco3'
callername4 : 'Fernando Verdasco4'
callername5 : 'Fernando Verdasco5'

this page automatically changes that name every 10 min

In this another page test1.php

I need a php code that takes only the name of the callername3 and echo’it

Fernando Verdasco3

I’ve tried this like so test1.php?id=callername3

<?php 
  $Text=file_get_contents("test.php");
  if(isset($_GET["id"])){
     $id = $_GET["id"];
     parse_str($Text,$data);
     echo $data[$id];
  } else {
     echo "";
  }

?>

but no result.

Is there any other option?

If i have “=” instade of “:”

callername1 = 'Fernando Verdasco1'
callername2 = 'Fernando Verdasco2'
callername3 = 'Fernando Verdasco3'
callername4 = 'Fernando Verdasco4'
callername5 = 'Fernando Verdasco5'

And i use This php Code it works

<?php 
    $Text=file_get_contents("test.php")
    ;preg_match_all('/callername3='([^']+)'/',$Text,$Match); 
    $fid=$Match[1][0]; 
    echo $fid; 

?>

i need this to work with “:”

Help?

There is a rather simple approach to tihs:

$fData = file_get_contents("test.php");
$lines = explode("n", $fData);
foreach($lines as $line) {
    $t = explode(":", $line);

    echo trim($t[1]); // This will give you the name
}
Read more
September 3, 2013

How to apply css class for selected element in jquery or javascript?

User2563516’s Question:

I am new to Jquery any one tell me how to select child elements
please check my code

<ul class="orglisting">
   <li><a href="javascript:getOrgUsers();" class="orglistactive">orgName</a></li>
   <li>
      <a href="javascript:getOrgUsers();">orgName1</a>
      <ul id="dId">
         <li id="dId1"><a href="javascript:getDeptUsers('Sales','1','1');">Sales</a></li>
         <li id="dId2"><a href="javascript:getDeptUsers('Engineering','1','1');">Engineering</a></li>
      </ul>
   </li>
   <li>
      <a href="javascript:getOrgUsers();">orgName2</a>
      <ul id="dId">
         <li id="itbhanu"><a href="javascript:getDeptUsers('ITbhanu','1','1');">ITbhanu</a></li>
      </ul>
   </li>
   <li>
      <a href="javascript:getOrgUsers();">orgName3</a>
      <ul id="dId">
         <li id="Engineering"><a href="javascript:getDeptUsers('PvtLtd','Engineering','1','1');">Engineering</a></li>
      </ul>
   </li>
</ul>

My problem is when i am select deparmentName i want to select change background color for parent tag(orgName) and selected deartmentName.

For Example i am selected in orgName1(orgName) in that i selected Enginnering (department) i want to change backgroundcolor for orgName1 and Engineering and again i selected orgName2 (orgName) and departmentName is ItBhanu i want to apply background color for those two and remove before apply background color.

How can i do this..

If I understand you correctly you are trying to remove some style from previous elements and apply news elements to New Ones.

First of all, create a class which shows elements has selected, something like:

.selected { background: #ddd; }

Then on jQuery you have to attach to the click event of your anchor a tags.

$("a").on('click', function() {
   //Now this is run when all `a` will be clicked

   //First lets remove selected class from previously selected items

   $('.selected').removeClass('selected');

   // And lets add selected to currect element and this parent

   $(this).addClasss('selected');
   $(this).parent('li').find('a:first').addClass('selected');


});
Read more
September 2, 2013

how to delete an array which contains a specified string

Zaz’s Question:

I have an array called “VALUES” that contains multiple arrays. In these array there is a field named “test”, I only want the arrays pointed out that contains the number 4 in the test field.

my current output for Values array:

Array ( 

[0] => Array ( [entry_id] => 41149 [o_number] => 000001 [test1] => 000001 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[1] => Array ( [entry_id] => 41142 [o_number] => 000202[test1] => 000202 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[2] => Array ( [entry_id] => 41103 [o_number] => 000003 [test1] => 000003 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[3] => Array ( [entry_id] => 41101 [o_number] => 000044 [test1] => 000044 [test2] => 1234 [lev] => Ja [fak] => Manuel/brev [beta] => 10 [test] => 2 ) 

[4] => Array ( [entry_id] => 41100 [o_number] => 000542 [test1] => 000542 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[5] => Array ( [entry_id] => 41088 [o_number] => 001231 [test1] => 001231 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 3 ))

desired output:

Array ( 

[0] => Array ( [entry_id] => 41149 [o_number] => 000001 [test1] => 000001 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[1] => Array ( [entry_id] => 41142 [o_number] => 000202[test1] => 000202 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[2] => Array ( [entry_id] => 41103 [o_number] => 000003 [test1] => 000003 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[3] => Array ( [entry_id] => 41100 [o_number] => 000542 [test1] => 000542 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ))

I tried with a foreach but it didn’t work

    foreach ($values as $key) 
    {
        if($key === 4)
        {
//This will only show
    print_r($key);

//delete array?

        }
    }

Try following codes:

foreach ($values as $key => &$value) 
{
   if($value['test'] != "4")
      unset($values[$key]);
}

var_dump($values);

Since you are using multidimensional arrays it is not that easy to check whether or not any array consists of that key, without traversing through it. In order to traverse, you can use foreach

foreach($values as $array) {
    //Now here you can check if the there is `test` index available or is of value `4`

    if(isset($array['test'])) && $array['test'] == '4') {
        //Only then output it
        var_dump($array);
    }
}

It is that simple.

Read more
September 1, 2013

Multi image in one image file

Monocular’s Question:

I’m fairly new in CSS web design. I found some website combine multi image in one image file. This is an example from Amazon :

http://g-ecx.images-amazon.com/images/G/01/x-locale/personalization/amznlike/amznlike_sprite_02._V196113939_.gif

And i really want to know how to do it in the best way. Is there any tool for combine image and get pixel position of each image to put them in CSS?

They are called CSS Sprites. You can google a lot of information. This techniques are used by most sites to reduce loading time. What you basically do is load one images in all the elements you want to load the images.

But you load them as their background images, thus enabling you to modifying their position. Thus making it possible to show different version of same images.

I dont want to tell everything so here is a futher read to get you started.

Read more
August 30, 2013

Shortened url redirect?

Huyimin’s Question:

I need help to get this done.

My webpages have formatted urls in this pattern: “http://qifu.us/index.php?page=item&id=4” for example – if there are more pages, only the last page id number will be different.

I want to get this part “index.php?page=item&id=” out, and shortened like “http://qifu.us/s4“, when a user input the shortened url into to address bar, it will be directed to the right page, which is the true url.

I am thinking to save the STATIC part “index.php?page=item&id=” into a string variable, and append the DYNAMIC page id – which is 4 in this example, then use Javascript or PHP to direct to the right page. But I don’t know how the steps, pls help. Thanks.

Actually an htaccess will be very good for this purpose.

For urls like http://qifu.us/s4 do the following: Create a file with name .htaccess and place at your root directory with the following content.

RewriteEngine On
RewriteRule ^s([^/]*)$ /index.php?page=item&id=$1 [L]
Read more
...

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