...

Hi! I’m Starx

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

setTimeout within function fails

Question by user1019490

This function accepts an argument, whichImage. This is the object HTMLImageElement for the image we are working with. The image width will be halved, and then after 3 seconds, it will return to normal width. However, the setTimeout code, which is supposed to execute after 3 seconds, fails, with the error message that whichImage is not defined. What do I need to correct to make this function work?

function resizeImageFunction(whichImage){
    // Get the width of the image
    alert(whichImage);
    var width = whichImage.width;
    var halfwidth = Math.round(width/2);
    whichImage.width=halfwidth;
    setTimeout("whichImage.width=width;",3000);
}

Answer by Starx

You don’t need to use eval for this

setTimeout(function() { whichImage.width=width; } ,3000);

Here is is your function

function resizeImageFunction(whichImage){
    var halfwidth = Math.round(width/2);
    whichImage.width=halfwidth;
    setTimeout(function() { whichImage.width=width; } ,3000);
}
Read more

Get option value depending on other element

Question by user1254282

I have the following html markup:

<div class="wrap_select">
    <span class="select" id="selectdateRange">Today, 25 March, Sun</span>
    <select class="styled" id="dateRange" name="dateRange">
        <option value="25.03.2012">Today, 25 March, Sun</option> // "current"
        <option value="26.03.2012">Tomorrow, 26 March, Fr</option>
        <option value="27.03.2012">27 March, Tu</option>
        <option value="28.03.2012">28 March, We</option>
        <option value="29.03.2012">29 March, Th</option>
    </select>
</div>

The <span class="select"> contain text from select options.
How can I get value of the “current” select?

For marup above the result must be 25.03.2012.

Answer by gdoron

var text = $.trim($('#selectdateRange').text());
var theWinner = $('select option').filter(function() {
    return $(this).text() == text;
}).val();

alert(theWinner);


LIVE DEMO

Answer by Starx

Here is an alternative way that does what you want

function findCurrent() {
    var currentText = $('span').text();
    var currentVal;
    $("select option").each(function(k,v) {
       if($(this).text()==currentText) {
           currentVal = $(this).val();
           return false;
       }
    });
    return currentVal;
}
// Usage
console.log(findCurrent());

Demo

Read more

Working with extended classes in PHP

Question by epic_syntax

I have 2 classes looking like this:

class db {

    protected $db;

    function __construct() {
        $this->connect();
    }

    protected function connect() {
        $this->db = new MySQLi(db_host, db_user, db_pass, db_name) or die($this->db->error);
        $this->db->set_charset('utf8');
    }

}

and

class sample extends db {

    protected $js_base_dir;

    public function __construct($js_base_dir = js_dir) {
        $this->js_base_dir = $js_base_dir . "/";
    }
 ....

I want to use $this->db inside second class, but __construct in sample class overrides first classes construct function. How to get $this-> db inside second class? Am I doung something wrong? if yes what’s proper way?

Answer by Starx

You can call parent class method, using parrent::methodName(). Similarly, you can use this to invoke parent’s constructor method as well as

parent::__construct();

Usage:

public function __construct($js_base_dir = js_dir) {
    parent::_construct();
    $this->js_base_dir = $js_base_dir . "/";
}

Apart from the manual read this article for extended explanation.

Read more
March 24, 2012

PHP Excel Header

Question by user794624

header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
header("Content-type:   application/x-msexcel; charset=utf-8");
header("Content-Disposition: attachment; filename=abc.xsl"); 
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
echo "Some Text"

Here is code to write and download xsl file using php,
my problem is when i open excel file MS-Excel show warning before opening file says

The file you are trying to open is in different format than specified by the file extension…Blah blah

What’s to do with PHP code to remove this warning. Contents are written correctly.

i know this is because content written in file are txt file content and file extension is incorrect, that is, xls. Solution???

Please don’t suggest to use any library.

Answer by Starx

You are giving multiple Content-Type headers. application/vnd.ms-excel is enough.

And there are couple of syntax error too. To statement termination with ; on the echo statement and wrong filename extension.

header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=abc.xls");  //File name extension was wrong
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
echo "Some Text"; //no ending ; here
Read more

How can I center an image of *unknown size* in a div, both vertically and horizontally?

Question by alexx0186

I am looking to handle files that were uploaded by users. The main issue in that situation is that they differ in size.

How can I center an image of unknown size, both vertically and horizontally, into a div?

Thanks a lot

EDIT: I am making a thumbnail for an image. Basically, I want to keep the div to the same size, and I want the image inside that div to fit the div, but without changing the scale. I am using overflow:hidden

EDIT:My code is

<div class='pic'><img id='theimage' src='image.png'></div>

and my CSS is

#theimage {
    vertical-align: middle;
    display: inline;

}

Answer by Starx

Force the container to behave as a table cell.

#container {
     display: table-cell; 
     vertical-align: middle; 
     text-align: center;
}

Demo

Read more

position:absolute within border-radius and overflow:hidden

Question by JaNightmare

I had a problem with border-radius in webkit browsers and found the solution at the following URL:
How to make CSS3 rounded corners hide overflow in Chrome/Opera

but iam using a another element with position: absolute; inside this
now I need to make the caption with rounded border too, but do not know how

note: i can’t use another border-radius in caption, because this will have an animation

see the code with:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Problem</title>  
    <style type="text/css"> 
    img {
        border: 0;  
    }

    a {
        text-decoration: none;  
    }

    .wrap-events {
        float: left;
        position: relative;
        width: 500px;
        height: 250px;
    }

    .events {
        overflow: hidden;

        -webkit-border-radius: 50px;
        -moz-border-radius: 50px;
        border-radius: 50px;
    }

    .caption {
        position: absolute;
        width: 100%;
        bottom: 0;
        color: #FFFFFF;
        background-color: #151515;
        font: 12px "Arial", Helvetica, sans-serif;

        opacity: 0.6;

        border-radius: 0 0 50px 50px; /* add border-radius to caption */
    }

    .caption p {
        padding: 10px;
    }
    </style>
</head>
<body>
    <div class="wrap-events">
        <div class="events">
            <a href="#">
                <img src="http://www.cg-auto.com.br/forum/imagens/imagens_news/26c4dc4359edcfd4c6871ee1fa958539.jpg" alt="image">
            </a>
            <div class="caption">
                <p>This is a caption</p>
            </div>
        </div>
    </div>
    <button id="slide">Slide It!</button>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        $('#slide').click(function(){
            $('.caption').hide().slideDown(2000);
        });
    </script>
</body>
</html>

cheers

Answer by Starx

That is a problem for now I think. May I suggest you use fadeIn() Instead. See a demo

Read more

jQuery play/pause jQuery function

Question by Yusaf

What I’m trying to do is play and pause a function ie press a button to start a fucntion press a button to pause so on. I am not entirely sure how this can be done i have tried .live() and .die() but they don’t work.

Fiddle

I have the HTML below

<button class="play">play</button>
<button class="pause">pause</button>
<div class="divafter"></div>​

and the jQuery which I’m not entirely sure what .die() does but on the jsfiddle seems to speed up the interval time.

(function($){
  playing = function() {
window.setInterval(function() {
    $(".divafter").after("playing <br/>");
}, 500);
};
})(jQuery);
$(".play").click(function(){
    playing().live();
});
$(".pause").click(function(){
    playing().die();
});​

Answer by j08691

Try this jsFiddle example. You need to use clearInterval() to stop setInterval().

jQuery:

var foo;
playing = function() {
    foo = window.setInterval(function() {
        $(".divafter").after("playing <br/>");
    }, 500);
}

$(".play").click(function() {
    playing();
});
$(".pause").click(function() {
    clearInterval(foo);
});​

Answer by Starx

You will have to the clearInterval to simulate the pause effect.

Grab the instance of the interval like this

playing = setInterval(function() {
            $(".divafter").after("playing <br/>");
          }, 500);

And clear to pause

clearInterval(playing);

Usage on your code would be this:

var playstatus;
(function($){
    playing = function() {
        return setInterval(function() {
           $(".divafter").after("playing <br/>");
           }, 500);
    };

})(jQuery);

$(".play").click(function(){
    playstatus = playing();
});
$(".pause").click(function(){
   clearInterval(playstatus);
});

Demo

Read more

How to change background color randomly in HTML with JavaScript?

Question by toky

this web page changes the backgrounder color randomly. i am having trouble to do the same thing with “#title” ,but the color stays the same.

please help

Thank you

JavaScript code:

function setbackground()
{
    window.setTimeout( "setbackground()", 80); //  milliseconds delay

    var index = Math.round(Math.random() * 9);

    var ColorValue = "FFFFFF"; // default color - white (index = 0)

    if(index == 1)
        ColorValue = "66FF33"; 
    if(index == 2)
        ColorValue = "FF0000"; 
    if(index == 3)
        ColorValue = "FF00FF"; 
    if(index == 4)
        ColorValue = "0000FF"; 
    if(index == 5)
        ColorValue = "00FFFF"; 
    if(index == 6)
        ColorValue = "FFFF00"; 
    if(index == 7)
       ColorValue = "CC66FF"; 
    if(index == 8)
        ColorValue = "3366FF"; 
   if(index == 9)
        ColorValue = "CCCCCC"; 

   document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue;

}

function setbackgroundTitle()
{
    window.setTimeout( "setbackgroundTitle()", 600); //  milliseconds delay

    var index = Math.round(Math.random() * 4);

    var ColorValue = "FFFFFF"; // default color - white (index = 0)

    if(index == 1)
        ColorValue = "66FF33"; 
    if(index == 2)
        ColorValue = "FF0000"; 
    if(index == 3)
        ColorValue = "FF00FF"; 
    if(index == 4)
        ColorValue = "0000FF"; 


    document.getElementById("title")[0].style.backgroundColor = "#" + ColorValue;

}

CSS code:

#title{
    background-color:#11f22f;
    height:300px;
    width:400px;
    margin:25px auto 0 auto;
    -moz-border-radius:25px;
    -webkit-border-radius:25px;
}

html Code:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>HomeWork</title>
        <script type="text/javascript" src="crazy.js"> </script>
        <link rel="stylesheet" type="text/css" href="HomeWork2.css" />

    </head>
    <body>

    <body onload="setbackground();">
        <div id="title" onload="setbackgroundTitle();"> hjhjhkj dfvdfsv dfgvkdfsk dfs</div>
    </body>
</html>

Answer by godlark

First, copy paste error: instead document.getElementById("title")[0].style.backgroundColor = "#" + ColorValue; there should be document.getElementById("title").style.backgroundColor = "#" + ColorValue;
According with that How to make a div onload function? doesn’t work.
I’ve put everything to setbackground() and it works 😉

Answer by Starx

The problem may be that the DOM wasn’t loaded when the script was running.

Correct your function to this, you are assuming the output of document.getElementById("title") as an array, but its not.

document.getElementById("title").style.backgroundColor = "#" + ColorValue;

And call it on the onload event, to ensure the DOM is loaded properly when the script runs

window.onload = function() {
 setbackgroundTitle();
};
Read more

PHP: How to Hide <br /> in Console

Question by Kinz

Okay, so I’ve got a program that converts nl2br, and prints the output to a console window. Though it prints along with the output data, the <br />. I’m fine with it and all, if I can’t remove/hide it without all the output melding together, but I’d rather hide/remove it if possible. Any suggestions are thankfully accepted.

-Example-
What console says:
: Output here!<br />
What I want:
: Output here!

I’ve tried substr($out, 5), trim(), and that’s all I could come up with. All those did was meld the output together.

Answer by ShinTakezou

It’s not totally clear, but I suspect you misuderstood nl2br. As the name suggests, it adds for each “newline” a “br” before, so that in HTML (which treats newlines like spaces in text) you will see actualy the text continuing in the next line. When you print to console, the console interprets usually the newline as a newline and so a new line begins. You do not have to use nl2br if you want to output “it” to console. (See nl2br for details).

Answer by Starx

That’s what nl2br() does, changes new line character n to <br />.

If you want, take those out, you can use str_replace()

str_replace("<br />", "", $output);
Read more

Scale text string to given width

Question by santa

Is it possible to scale a text string’s size with CSS or jQuery if the width of the allocated space is known? I need it to increase font size without wrapping the string.

Let’s say I have something like this:

<div style="width:600px">My text string here.</div>

I suppose I could measure the width by wrapping the string in span

JS:

var strWidth = $("#myStr").width(),
    strFontS = 20;

if (strWidth < 600) {
    // maybe increase font-size
    $("#myStr").css("font-size", strFontS + 1 + "px");
}

HTML:

<div id="myDiv" style="width:600px"><span id="myStr">My text string here.</span></div>

Answer by Starx

Here is a plugin I made, which you can use to resize the text

$.fn.resizeText = function(){
  var size = parseInt($(this).css("fontSize"));  
  var html = $(this).html();
  var textLength = html.length;
  var span = '<span>' + html + '</span>';
  $(this).html(span);
  var width = $(this).find('span:first').width();
  $(this).html(html);
  var newSize = $(this).width()/width*size;
  $(this).css("fontSize", newSize);
  return width;
};

Usage:

$("div").resizeText();

Check out the demo.

Read more
...

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