...

Hi! I’m Starx

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

Catch browser's "zoom" event in JavaScript

Question by user123093

Is it possible to detect, using JavaScript, when the user changes the zoom in a page?
I simply want to catch a “zoom” event and respond to it (similar to window.onresize event).

Thanks.

Answer by Ian Elliott

There’s no way to actively detect if there’s a zoom. I found a good entry here on how you can attempt to implement it.

I’ve found two ways of detecting the
zoom level. One way to detect zoom
level changes relies on the fact that
percentage values are not zoomed. A
percentage value is relative to the
viewport width, and thus unaffected by
page zoom. If you insert two elements,
one with a position in percentages,
and one with the same position in
pixels, they’ll move apart when the
page is zoomed. Find the ratio between
the positions of both elements and
you’ve got the zoom level. See test
case.
http://novemberborn.net/javascript/page-zoom-ff3

You could also do it using the tools of the above post. The problem is you’re more or less making educated guesses on whether or not the page has zoomed. This will work better in some browsers than other.

There’s no way to tell if the page is zoomed if they load your page while zoomed.

Answer by Starx

There is a nifty plugin built from yonran that can do the detection. Here is his previously answered question on StackOverflow. It works for most of the browsers. Application is as simple as this:

window.onresize = function onresize() {
  var r = DetectZoom.ratios();
  zoomLevel.innerHTML =
    "Zoom level: " + r.zoom +
    (r.zoom !== r.devicePxPerCssPx
        ? "; device to CSS pixel ratio: " + r.devicePxPerCssPx
        : "");
}

Demo

Read more
January 17, 2013

Forcing <table> Columns to a Fixed Width; Prevent Automatic Expand

Question by Chad Decker

I generally set fixed column widths via CSS with flawless results:

#tableID thead tr th:nth-child(1){width: 75px;} 
#tableID thead tr th:nth-child(2){width: 75px;}
/* etc… */

But now I’m in a situation where I won’t know the desired column widths until runtime. Here’s an excerpt from the code I’m using to dynamically set the column widths:

var tr=$("<tr>");
var colArr=Home.ColDefs[this.statBatchType].colArr;
for(var i=0;i<colArr.length;i++){
    var col=colArr[i];
    tr.append(
        $("<th>")
            .html(col.title)
            .css("width",col.width)
    );
}
this.jqTHead.append(tr);

Sorry this code is a bit out of context but the bottom line is that I’m adding columns, represented by <th> elements, to a table header and setting each one’s width.

What ACTUALLY happens, however, is that Firefox is treating the column width as a minimum and then automatically expanding the column width as the user expands his browser window. Consider a case where my JavaScript code sets the width of each column to 75px. Firefox will ensure each column is at least 75px wide, but if the user maximizes (or enlarges) his browser, provided there is sufficient room, each column will be automatically widened.

This is odd to me since the JavaScript code would seem to be the functional equivalent of what I was doing in CSS. Yet the CSS approach doesn’t cause this odd behavior.

Any thoughts?

Answer by Starx

You can assign a class selector with the required css and then assign it later when you need it on runtime.

.fixed {
   width: 50px;
}

And assign them when you want in run time.

$("th").addClass('fixed');
Read more
January 14, 2013

How do I set background color of text only in CSS?

Question by Hithere Paperbag

enter image description here

What I want is for the green background not to be 100% of the page width.
I want it just behind the text.
Html:

<!DOCTYPE html>

<head> 
<link rel="stylesheet" type="text/css" href="style.css">
</head> 

<body> 

<h1>  
The Last Will and Testament of
Eric Jones</h1> 

</body> 

style.css:

h1
{ 
    text-align: center; 
    background-color: green; 
}

Answer by BalusC

Put the text in an inline element, such as a <span>.

<h1><span>The Last Will and Testament of Eric Jones</span></h1>

And then apply the background color on the inline element.

h1 {
    text-align: center; 
}
h1 span { 
    background-color: green; 
}

An inline element is as big as its contents is, so that should do it for you.

Answer by Starx

A very simple trick to do so, is to add a <span> tag and add background color to that. It will look just the way you want it.

<h1>  
    <span>The Last Will and Testament of Eric Jones</span>
</h1> 

And CSS

h1 { text-align: center; }
h1 span { background-color: green; }

WHY?

<span> tag in an inline element tag, so it will only span over the content faking the effect.

Read more
December 23, 2012

How to print just a few from an array instead of all in php

Question by Marqeeu Rahfis

This is part of the working code that shows the entire array;

$files = filelist("./",1,1); // call the function
shuffle($files);
foreach ($files as $list) {//print array
echo "<a href="" . $list['name'] . "$startDir"><h4> " . $list['name'] . " </h4></a>";
//    echo "Directory: " . $list['dir'] . " => Level: " . $list['level'] . " => Name: " . $list['name'] . " => Path: " . $list['path'] ."<br>";

How do I modify it so that it only displays 10 or 15 list instead of all?

Answer by Starx

If you know the keys or indexes of the array you can do what KingCrunch is doing a lot faster by simple for loop

for($i=0; $i<=14; $i++) {
   // echo $file[$i];
}
Read more
December 20, 2012

Call to undefined method PHP_CodeCoverage_Filter::getInstance()

Question by beanland

I’ve got a fresh copy of PHPUnit installed on my system (Ubuntu 11), but whenever I type phpunit in the console I get the following error:

PHP Fatal error: Call to undefined method PHP_CodeCoverage_Filter::getInstance() in /usr/bin/phpunit on line 39

I have PHPUnit’s code coverage installed, as far as I know:

>sudo pear install phpunit/PHP_CodeCoverage

phpunit/PHP_CodeCoverage is already installed and is the same as the released version 1.1.1

install failed

Why am I getting this error and how can I fix it?

Answer by David Harkness

The executable script that loads PHPUnit must not have been updated when going to 3.6.x. Reinstall it.

sudo pear uninstall phpunit/PHPUnit
sudo pear install phpunit/PHPUnit

If this doesn’t work, make sure PEAR itself is up-to-date.

Answer by Starx

For some, Anthony’s solution will not work fully because of the Unknown remote channel: pear.symfony.com or phpunit/PHPUnit requires package "channel://pear.symfony.com/Yaml".

SO here is the upgraded solution that solves this:

sudo apt-get remove phpunit

sudo pear channel-discover pear.phpunit.de

sudo pear channel-discover pear.symfony-project.com

sudo pear channel-discover components.ez.no

sudo pear channel-discover pear.symfony.com

sudo pear update-channels

sudo pear upgrade-all

sudo pear install pear.symfony.com/Yaml

sudo pear install --alldeps phpunit/PHPUnit

sudo pear install --force --alldeps phpunit/PHPUnit
Read more
December 9, 2012

Get count of columns MySQL

Question by user1868569

How can i get the count of columns in my table, searched google through, but can’t find a straight answer.

Thank you in advance.

Answer by Starx

Such information are located in INFORMATION_SCHEMA you can query a table called COLUMNS to get the number of columns in a database.

This query will give you the column count.

SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'DB_NAME' AND table_name = 'TABLE_NAME'
Read more
November 23, 2012

execute string as javascript function

Question by chugh97

My object has a call back:

var MyObject = {
CallBack: "function (whichSubMenuIsClicked, subMenuObjectTag) { self.doStuff(whichSubMenuIsClicked.SubMenuItem, whichSubMenuIsClicked.HeaderColumnName, whichSubMenuIsClicked.DivIdentifier);}",
}

The callback is a string. Now I need to execute it using MyObject.CallBack(param1, param2)
How can this be done using jquery or javascript. The self in this case is the original widget calling another widget. Thus the call back is on the original widget.

Answer by Starx

Very bad approach but You can do it by eval()

var MyObject = { CallBack: "AName = function(param1, param2) { alert(param1 + param2); }", }

eval(MyObject.CallBack+"(1,2)"); 

Demo

Read more
November 16, 2012

Block access to files and sub directory with .htaccess?

Question by jaya malladi

I have nearly 30 php files, 4 sub directories in my directory. I want to block some php files and sub directories from user in direct viewing like http://bhavani.com/hai.php

My currect htaccess file

## Enable Mod Rewrite, this is only required once in each .htaccess file
RewriteEngine On 
RewriteBase / 
## Test for access to includes directory
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /includes/ .*$ [NC] 
## Test that file requested has php extension 
RewriteCond %{REQUEST_FILENAME} ^.+.php$ 
## Forbid Access 
RewriteRule .* - [F,NS,L]

How to do it?

Answer by Starx

You can filter the files like this

<Files ~ ".php$">
  Deny from all
</Files>

And directory like this

<Directory "/subdirectory">
  Deny from all
</Directory>
Read more
November 14, 2012

Show delete message URL based on username

Question by user1793122

I have an PHP + Jquery wall message that show all message from anybody. Now I want to set delete URL in every messages. But the rule, user can’t see delete url if the messages is not his own.

.childs {
opacity: 0;
color: #000;
margin-left: 10px;
float: right;
}

.childs:hover {
opacity: 1.0;
text-decoration: underline;
cursor: pointer;
}

.parents:hover > .childs {
opacity: 1.0;
}


This logged in as Greg

<section class="parents">
Greg : Today is holiday
<div class="childs"><a href="delete.php">Delete</a></div>

This logged in as Jeremy

<section class="parents">
Jeremy : Beautiful day
<div class="childs"><a href="delete.php">Delete</a></div>

I want the Delete link show based on username logged in. So if Jeremy mouse over Greg message, delete link will not show because it’s not his message and if Greg mouse over his own message, he can see the delete url link and can delete it.

So how can I set that ?
Thanks for helps.

Answer by Starx

This is a simple approach. Store the logged in information of session using $_SESSIONthen compare this on your view class/code.

Like

<div class="childs">
<?php
if($_SESSION['logged_in_user'] == true) { 
   echo "<a href='delete.php'>Delete</a></div>";
}?></div>
Read more
November 11, 2012

Adding easing to the following jQuery animation?

Question by alexchenco

I’m animating the height of element:

  // Animate height of items
  $j(".item .row").toggle(function(){
    $j(this).animate({height:500},200);
  },function(){
    $j(this).animate({height:300},200);
  });

I was wondering how to add easing to it? (e.g. the animation slowing down towards the end?)

Answer by Starx

Define easing, the following way

$('selector').animate({
    prop:1
},{
    easing: easing, //Something like 'linear'
    duration: duration,
    complete: callback
});

You can add other easing effects also, by including the Easing Plugin.

In your case, it would be something like

$j(".item .row").toggle(function(){
    $j(this).animate({height:500}, {
        easing: 'linear',
        duration: '200'
    });
  },function(){
    $j(this).animate({height:300},{
        easing: 'linear',
        duration: '200'
    });
});
Read more
...

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