...

Hi! I’m Starx

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

Clone of a div changing as the original div is being changed

Question by Bhumi Singhal

I have a div “maindiv”. This further has divs inside it including “imagediv”. In jQuery, I write :

$(document).ready(function() {

    ......

    var copydiv = $('#maindiv').clone();
    var number = 1;
    $("body").delegate("#imagediv", "mousedown", function(event) {

        $("#maindiv").attr('id', "changedmain" + number);
        $("#imagediv").attr('id', "changedimage" + number);
        copydiv.insertAfter("#appendafter");
        number = number + 1;
    });
});​

HTML:

<div id="appendafter"></div>
<div id="maindiv">
.
.
.
</div>

For this code, for the first time after copydiv is appended, the clone that is added has id as “maindiv” and all the inner divs have the correct it.But when number is 2, the clone contains “changemain2” instead of maindiv.WHY is this?? Any remedy ????

Answer by Starx

First, Id’s have to unique in a DOM. On this, case where you are appending multiple sets, switch to class selectors.

Next, your variable number is local and redefined and reset to 1 on every mousedown

var copydiv = $('.maindiv').clone();  
var number = 1; // This was redefined and set as 1 on every `mousedown` 
                // So make it global

$("body").delegate(".imagediv","mousedown",function(event){       
    $(".maindiv").attr('class',"changedmain" + number);
    $(".imagediv").attr('class',"changedimage" + number );
    copydiv.insertAfter("#appendafter"); // You might have to change this too 
                                         // depending if this is repeated too
    number = number+1;
}

Also, It is preferable to delegate using a .on() function

$("body").on("mousedown", ".imagediv", function(event){       
    $(".maindiv").attr('class',"changedmain" + number);
    $(".imagediv").attr('class',"changedimage" + number );
    copydiv.insertAfter("#appendafter"); // You might have to change this too 
                                         // depending if this is repeated too
    number = number+1;
}

Solution:

The problem was with the method used. Elements cloned using .clone() will hold the reference, so instead of adding a new element it will keep updating previously referenced objects.

Here is the solution:

var number = 1; //Our Counter Script

function createDiv() {
    //Lets create a new div, 
             // I mean WHY CLONE AT the first place?? 
             // We are delegating events anyway :p

    $("<div />", {
        html : $('#maindiv').html(), // add the HTML of div we are trying to keep
             // ^ Better used cached 
             //   version is not updated regularly

        id : "maindiv-"+number       // add the generate id number 
    }).insertAfter("#appendafter");  // Now insert it
    number++;
}

$("body").on("mousedown", ".imagediv", function(event){
    createDiv(); //Delegating on all elements with `imagediv` class
});

Demo

Read more

PHP email issue

Question by user1802398

I’ve a HTML signup form with php. After a successfully submit it sends a confirmation email to the user email address.

Well, when user see his/her email it’s shown as:

Yoursite.comr@mediaplan.ovh.net

But I didn’t add the @mediaplan.ovh.net part to the email address. Why it’s showing in this address. @mediaplan.ovh.net? and how do i remove it?

php email code:

$to = "$email";                     
$subject = "Signup | Verification";
$message = "Congratulation $f_name $l_name you have been successfully registered. 
Please click the link to active your account.rn";
$message .= "http://www.maaks.fr/hotel/verify.php?email=$email&hash=$hashrn";

$from = "Yoursite.com";
$headers = "MIME-Version: 1.0rn";
$headers .= "Content-rype: text/html; charset=iso-8859-1rn";
$headers .= "Content-Transfer-Encoding; 7bitrn";
$headers = "From:" . $from . "rn";

$mailsent = mail($to,$subject,$message,$headers); 

Answer by Starx

First, You are missing a slash in your from header part.

$headers = "From:" . $from . "rn";
                          //  ^ Here

Change From headers while sending the mail

$from = "WebsiteName <Your@mail.com>";
$headers = "MIME-Version: 1.0rn";
$headers .= "Content-rype: text/html; charset=iso-8859-1rn";
$headers .= "Content-Transfer-Encoding; 7bitrn";
$headers = "From: " . $from . "rn";
Read more

How to read a file line by line in php

Question by adnan masood

How to read a file line by line in php, without completely loading it in memory.
Becuase my file is too large to open in memory so i always got memory exhaust error.
The file size is 1Gb.

Answer by Starx

Use buffering techniques to read the file.

$filename = "test.txt";
$source_file = fopen( $filename, "r" ) or die("Couldn't open $filename");
while (!feof($source_file)) {
    $buffer = fread($source_file, 4096);  // use a buffer of 4KB
    $buffer = str_replace($old,$new,$buffer);
    ///
}
Read more

File replace in upload in php

Question by Mervyn

I would like to delete a file that is already exists and add the new one in the same folder.
I have taken the tmp name added it in a session. Deleted the existing already but it not movin in the new one.

<?php
session_start();
$files = $_SESSION['Already'];
$tmp=$_SESSION['PATH'];
unlink('../upload/'.$files);
$to="../upload/".$files; 
move_uploaded_file($tmp,$to);
?>

Answer by Starx

Try replacing the files. If the files name are exactly same, you don’t need to unlink them. Just using move_uploaded_file() will do.

Its important to know what is causing the error. Check your server error_logs for such informations.

Read more

How to dynamically create a string in PHP?

Question by All

I have a predefined pattern for building a string, which should be created regularly throughout the script.

$str="$first - $second @@ $third"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";
$string= ..?? // string should be built here based on the pattern

Currently, I am using eval to generate the string in place based on the pattern originally defined. However, as this happens occasionally and eval is generally bad, I wish to find another method.

NOTE that the pattern is defined only one time above all codes, and I can edit the pattern of all the script by one line only. Thus, what makes $string should not be touched for any change.

I tried create_function, but needs the same number of arguments. With eval, I can easily change the pattern, but with create-function, I need to change the entire script. For example, if changing the string pattern to

$str="$first @@ $second"; // One arg/var is dropped

eval Example:

$str="$first - $second @@ $third"; // Pattern is defined one-time before codes
$first="word1";
$second="word2";
$third="word3";
eval("$string = "$str";");

create_function Example:

$str=create_function('$first,$second,$third', 'return "$first - $second @@ $third";');
$string=$str($first,$second,$third);

Answer by Vulcan

You can use the string formatting capabilities offered by sprintf or vsprintf.

$format = "%s - %s @@ %s"; // pattern for building the string
$first = "word1";
$second = "word2";
$third = "word3";
$string = sprintf($format, $first, $second, $third);

You can use vsprintf if you wish to pass an array.

$format = "%s - %s @@ %s"; // pattern for building the string
$values = array($first, $second, $third);
$string = vsprintf($format, $values);

Answer by Starx

Seems to be rather simple thing to me. Use str_replace() and replace based on patterns

$str="$first$ - $second$ @@ $third$"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";

$newstr = str_replace('$first$', $first, $str);
$newstr = str_replace('$second$', $second, $newstr);
$newstr = str_replace('$third$', $third, $newstr);
Read more

Find ratio for any number of variables in php?

Question by neha thamman

I want to find ratio for any number of variables in php.

For example: 1:2 10:100:50
30:90:120:150

How can I get such rations?

Answer by Starx

One way would be convert the values to decimal values and covert them to fraction.

I found a function that will do this: [Source]

function decToFraction($float) {
    // 1/2, 1/4, 1/8, 1/16, 1/3 ,2/3, 3/4, 3/8, 5/8, 7/8, 3/16, 5/16, 7/16,
    // 9/16, 11/16, 13/16, 15/16
    $whole = floor ( $float );
    $decimal = $float - $whole;
    $leastCommonDenom = 48; // 16 * 3;
    $denominators = array (2, 3, 4, 8, 16, 24, 48 );
    $roundedDecimal = round ( $decimal * $leastCommonDenom ) / $leastCommonDenom;
    if ($roundedDecimal == 0)
        return $whole;
    if ($roundedDecimal == 1)
        return $whole + 1;
    foreach ( $denominators as $d ) {
        if ($roundedDecimal * $d == floor ( $roundedDecimal * $d )) {
            $denom = $d;
            break;
        }
    }
    return ($whole == 0 ? '' : $whole) . " " . ($roundedDecimal * $denom) . "/" . $denom;
}

Now

$total = 1 / 2;
echo decToFraction($total);

Or, you could use PEAR’s Math_Fraction [Source]

include "Math/Fraction.php";

$fr = new Math_Fraction(1,2); //Put your variable like this    

// print as a string
// output: 1/2
echo $fr->toString();

// print as float
// output: 0.5
echo $fr->toFloat();
Read more

Why is "display: table-cell" messing up my div's?

Question by eric01

I’m trying to center the strings “1”,”2″ and “3” vertically as seen here:

But when I use display: table-cell; vertical-align: middle; for all 3 div’s, but then I get his unwanted result:

HTML is

<div id='alldivs'>
    <div id='red' class='each_div'>1</div>
    <div id='blue' class='each_div'>2</div>
    <div id='green' class='each_div'>3</div>

</div>

CSS is

.each_div { 
     width: 80px;
     height: 50px; 
     text-align: center;
     display: table-cell; vertical-align: middle;
}

Demo

How do I keep the 3 div’s aligned vertically while keeping vertical alignment within each div?

Answer by Starx

This is a conceptual misunderstanding. Without a parent element with display:table-row the tables cell will always span over full width, because it will create anonymous table object of table-row and table.

According to W3C Specification article: Tables

Document languages other than HTML may not contain all the elements in the CSS 2.1 table model. In these cases, the “missing” elements must be assumed in order for the table model to work. Any table element will automatically generate necessary anonymous table objects around itself, consisting of at least three nested objects corresponding to a ‘table’/’inline-table’ element, a ‘table-row’ element, and a ‘table-cell’ element. …..

Here is a quirksmode page showing uses of display: table and so on. A image showing the same effect as on this question.

To solve this problem semantically, you have to add an extra element to display as row.

<div id='alldivs'>
    <div id='red' class='each_div'>
        <div class="cell">1</div>
    </div>
    <div id='blue' class='each_div'>
        <div class="cell">2</div>
    </div>
    <div id='green' class='each_div'>
        <div class="cell">3</div>
    </div>
</div>

Then assign relative CSS to them

#alldivs { display: table; }

.each_div {
     display: table-row;
}

.cell {     
    width: 80px;
    height: 50px;
    display: table-cell;
    vertical-align: middle;
    border: 1px #000 solid;
}

Demo

Read more
November 5, 2012

scrolltop() is not work smoothly in chrome & safari but work in firefox

Question by sandeep

If you check this link http://jsfiddle.net/Hbkdt/.

$(window).scroll(function() {
       $(".fixed").css("top", $(window).scrollTop() + "px");
    });

Move your scroller downward. Then you can saw the .fixed DIV work smoothly in FF but it’s not work smoothly in Safari & Webkit.

I don’t know how can i fix it. Any help is appreciated 🙂

I am using Chrome Version 22.0.1229.94 in mac.

Answer by Starx

I am suggesting an alternative. The most favorable option to give to the smooth effect is to animate the change in position, to fake the easing.

Something like this

$(window).scroll(function(){
    $(".fixed").stop(false, true).animate({ "top" : $(window).scrollTop()}, 1000); 
});

Demo

This works great but when you starting scrolling with the scroll pane it starts stammering again.

But, to overcome this, you can use of debouncing techniques.

$(window).scroll(function(){
    $.doTimeout( 'scroll', 250, function(){
                         // ^ This time prevents the following code to run, 
                         //   if another scrolling occurs within this time

                         //   Thus enabling us to give a smooth scroll effect
                         //   Once the user is done scroll

        $(".fixed").stop(false, true) //break the queue fast
                   .animate({ "top" : $(window).scrollTop()}, 200);
    });
});

Demo

Read more
November 4, 2012

?: Operator return void

Question by Artur Keyan

I want to use the ?: operator intstead of if else

e.g.

var directory = new DirectoryInfo(path);
if (!directory.Exist())
{
    directory.Create();
}
else 
{
    // do nothing
}

I tried to use ?: like this:

var directory = new DirectoryInfo(path);
!directory.Exist() ? directory.Create() : void;

but it says “Invalid expression term ‘void’“, null also isn’t working.

Can anyone tell me a solution? Thanks.

Answer by Starx

Ternary operator are not designed to replace if/else They are to simplify assignment and declaration. It should be able to assign the result the statement to something like variable or function. There major use are in assignment or reading.

Something like

var status = !directory.Exist() ? directory.Create() : false;

The correct solution would be to stick to native if condition. The following is enough:

var directory = new DirectoryInfo(path);
if (!directory.Exist())
{
    directory.Create();
}
Read more

100% height of content – px

Question by Vladimir

I have a page with height 100%:

<div id="wrapper">
    <header id="header" class="clearfix">

    </header>
    <div class="main-container clearfix">
        <aside id="sideLeft">

        </aside><!-- #sideLeft -->
        <div id="content">
            <div id="map_canvas"></div>
        </div>
    </div> <!-- #main-container -->
</div><!-- #wrapper -->

CSS:

* {
    margin: 0;
    padding: 0;
}
html, body {
    height: 100%;
    min-height: 100%;
}
#wrapper {
    width: 100%;
    height: 100%;
}
#header {
    width: 100%;
height: 45px;
}
.main-container {
    width: 100%;
    height: 100%;
    min-height: 100%;
}

#content {
    height: 100%;
margin-left: 20%;
}

#map_canvas {
    height: 100%;
    width: 100%;
}
#sideLeft {
    height: 100%;
    width: 20%;
    float: left;
}

But I want to make content 100% – height of header (in px), to don’t show scrolling on the page.

I try to add position: absolute; to #header and .main-container but it’s not helping (scroll still showing).

Live example: http://indoor.powerhtml.ru/30/index.html

Answer by Starx

CSS cannot perform calculations and manipulation on page, it is just a stylesheet. You have to use JS for this.

jQuery snippet to do what you want is

$("#header").height($("#header").height()); //This automatically converts % to px

Check it out

Read more
...

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