...

Hi! I’m Starx

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

JavaScript test if a CSS stylesheet is applied with CSS3 media query

Question by Craig Francis

I have two style sheets:

<link rel="stylesheet" type="text/css" href="/core.css" media="screen" />
<link rel="stylesheet" type="text/css" href="/core-desktop.css" media="only screen and (min-width: 800px)" id="css-desktop" />

The second one should only be loaded when the window is 800px or wider (narrower displays get a layout more appropriate for mobile devices).

The JavaScript needs to know if that second style sheet is being applied, I have tried the jQuery:

($(window).width() > 800)

But when you get around the 790 – 810px width, Chrome/Firefox (and probably others) will return a value such as 791, and the 800px+ style sheet will still be loaded.

I suspect it’s due to the scroll bar (but targeting the $(document) or $(‘html’) either doesn’t work, or are the same).

So is there a way to test if $(‘#css-desktop’) is enabled/active/used?

Answer by Niels

You can do the following.

  1. Make a div which has a display: none; in the first stylesheet, so it is not shown.
  2. In the second stylesheet you will add a position: absolute
  3. In your Javascript you check if( $("#thediv").css("position") == "absolute")

The position: absolute; is only applied in the second stylesheet.

Answer by Starx

There is a problem with what you are attempting.

If a user is browsing the page while resizing the window below 800px in width then, he will get the mobile version of the page and later when he/she maximizes, he will still get the mobile version.

So, relying on screen width are not a reliable method as the screen resolution of the mobiles are growing significantly nowadays.

Your best shot is to read the User Agent information of the browser, which will easily reveal whether it is a mobile browser or other and load the css files according to it. Then for the variable screen resolution, you can use your current techniques to load width specific codes.

Read more

How to change the label text in javascript function?

Question by user1047651

i want to validate login page using java script function.
i take one label button for displaying message and two text box for username and password and one button for “Login” .

when user click on “Login” button without enterning username and password then message will be display in label control. So how to check textbox value in javascript function and how to change the value in lblmessage. I call this function in Ok button . I set this function on Button OnClientClick event but this does not work.

Answer by Starx

With javascript

A simple example

var lblElement = document.getElementbyId("yourlabelsid");

lblElement.innerHtml("Your new updated text in the label");

But try to use a javascript libray like jquery, it has a lot of benefits and ease.
Generically on jquery, to change the markup of any element, we use

$("#theselector").html("the new markup inside the markup");

In case input elements, we use .val();
$(“#mytextbox”).val(“the value in the textbox”);


Based on your description, you want to change the text inside label so a simple example

For this label

<label id="lbl_name">Name:</label>

Use

$("#lbl_name").html("the updated html"); 

Anywhere you need on the script

Read more
November 17, 2011

My First Blog

Today, November 17, 2011 13: 11 (GMT + 5:45), I am composing my first blog ever. My name is Nabin Nepal. I am 20 year 7 months 12 day 3 hours old, living in a small area of Budhanilkantha in Kathmandu. Professionally I am a programmer. Academically, I am doing my undergrad. I am invisible to most of people (I actually like it that way ;)), but among those who see me I am known as Nabin to most, as Starx to some, as neo to very few & as Knobin, to a special friend Kabir Basnet, who thought of this name…… and also became the name of my blog — — —

Read more
November 6, 2011

How to define custom attributes while appending a js file in Zend Framewok?

Question by mrN

I am trying to implement content flow in my zf application. And while loading its attributes, it requires one extra attribute to be defined.

<script type="text/javascript" src=".." load="white"></script>

To interprete this using zf, i tried

$this -> headScript() -> appendFile("my/path/to/contentflow.js","text/javascript", array("load" => "white")); 

But its not working.

How to do this?

Answer by Starx

Zend Framework does not allow such random attributes. If you really have to use them, you have to enable them using

$this -> headScript() -> setAllowArbitraryAttributes(true);
Read more
November 3, 2011

alternating row colors

Question by meandme

I am looking for a solution to use the alternating colors row design in my table which is from a csv.

my code:

<?php
echo "<table style='text-align: left; width: 99%;' border='1'>nn
<thead>
<tr>
<th>data</th>

</tr>
</thead>";
$f = fopen("local/datafiles.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr class='odds'>";
        foreach ($line as $cell) {
                      echo "<td style='font-weight: bold;'>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>n";
}
fclose($f);
echo "n</table>";
?>

so how can i have the tr class to alternate from odds and even?
thanks

Answer by OptimusCrime

<?php
echo "<table style='text-align: left; width: 99%;' border='1'>nn
<thead>
<tr>
<th>data</th>

</tr>
</thead>";
$f = fopen("local/datafiles.csv", "r");
$i = 0;
while (($line = fgetcsv($f)) !== false) {
    echo "<tr style='background-color: ".(($i%2)?'green':'blue').";'>";
    foreach ($line as $cell) {
        echo "<td style='font-weight: bold;'>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>n";
    $i++;
}
fclose($f);
echo "n</table>";
?>

Or you could assign a class just the same way and style it using css. This is much better practice.

Answer by Starx

I will give you a better but much simpler solution, through CSS. First of all uniquely identify your table, i will show you a more general option.

table tr { backgroun: #ddd; }
table tr:nth-child(2n) { background: #ccc; } 
Read more

how can I detect page when I compile all javascript to one file

Question by guilin 桂林

I compile all my javascript for different pages into one file, so I have to identify page for my all.js. I can put a hidden element in my pages and let javascript detect this element, but I don’t like this solution, are there any other ways to do this?

Answer by Starx

If you script is based on pages, then compiling them into one script is a bad idea, load the file separately, it will be lighter and definately increase some performace.

Read more
October 19, 2011

how to protect php page used by jquery ajax call

Question by domino

I just finished coding my first jquery ajax call page. It calls a php page every 1 or 2 seconds and returns json data.

The page basically displays posts of the message board the user is viewing. There are multiple message boards and some users should not be able to view certain boards, however the same php page is used for the call. It pics out the message using $id that is sent by the ajax script.

My question is how would I protect the php page from being manipulated and opened directly? The user can easily change the board id by opening the file directly and changing the URL. Not to mention the other ways.

If there is no easy way, then I guess I’d have to duplicate the majority of the main page to check if the user has necessary permissions. That would mean more server load since the page is updated every second.

Answer by TheVillageIdiot

Ajax calls are treated by server in the same way as normal page requests. All the authentication and authorization mechanisms are called before serving the page. To make sure just log off and try to get stuff from your page using AJAX. It should not work if your page requires you to log into the site.

Answer by Starx

If an AJAX call can open the page, so can the user, you cannot rely on definitive technique to protect a page. Rest you can follow what @TheVillageIdiot has said in his answer.

Read more
October 14, 2011

How to prevent SQL Injection attack in applications programmed in Zend Framework?

Question by Kamil Mroczek

I don’t have any concept about ZF safety. Do I have to use Filter when operating on database? Maybe binding is enough ? How about this:

$users->update($data, 'id=1');

Should $data array be filtered somehow ? Feel free to write anything you know about the issue.

Could you give some links to good articles about safety in ZF (mainly about SQL Injection and XSS)?

Answer by Gordon

Short answer
While ZF takes and provides some measures to secure your app, you should still apply the same precautions that you’d use without Zend Framework.


Regarding your code snippet, check out the Chapter on Zend_Db in the Reference Guide:

By default, the values in your data array are inserted using parameters. This reduces risk of some types of security issues. You don’t need to apply escaping or quoting to values in the data array.

This doesn’t mean you don’t have to bother about security. For instance, for the Update method above

The third argument is a string containing an SQL expression that is used as criteria for the rows to change. The values and identifiers in this argument are not quoted or escaped. You are responsible for ensuring that any dynamic content is interpolated into this string safely. See Quoting Values and Identifiers for methods to help you do this.

Note since you are using Zend_Db_Table obviously, third argument is second argument. Internally, the table instance will delegate the call to the db adapter with the first param being the table instance’s tablename.


Regarding Zend_View and XSS attack vectors:

Zend_View comes with an initial set of helper classes, most of which relate to form element generation and perform the appropriate output escaping automatically.

Again most of which does not mean all. Zend_View does provide Zend_View::escape() to help you sanitize output, but this nothing special.

Answer by Starx

I will suggest the Use of Zend Filters, wherever you need something specific. You can use this at anypoint in your application.

Request Parameter

$alpha = new Zend_Filter_Alpha();
$name = $alpha -> filter($this -> _request -> getParam('name')); //while processing url parameters

Database

$int = new Zend_Filter_Int();
$select -> where("id = ?", $int -> filter($id)); //during db processing also

Also in Form Elements . I will skip this as example of this can be found abudantly.

Read more
September 28, 2011

CSS Multiple grouped elements with margins

Question by Marty Wallace

Take this HTML:

<div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
</div>

With the companion CSS:

div.block
{
    float: left;
    width: 100px;
    height: 100px;
    margin: 1px;
    background: red;
}

The result of this is four blocks, which have between them 2 pixels of space (1px from the right margin of the left block and 1px from the left margin of the right block).

Is there a way that I can achieve a similar effect to border-collapse? ie. I want there to be only one pixel of margin between adjacent blocks.

This is a basic example of often more complex situations that I run into, and I don’t want to get around it by by anything similar to only setting margin-left to 1 pixel etc.

Answer by Starx

There are multiple ways to this

One of them is

div.block
{
    float: left;
    width: 100px;
    height: 100px;
    margin: 1px 1px 1px 0;
    background: red;
}
div.block:last-child {
    margin: 1px 0 1px 0;
}

Another is

div.block+div.block { margin-left: 1px; }

You can check the demo of both way here

Read more
September 26, 2011

How can I change the text of a <span> element?

Question by Sheehan Alam

I have a toggle button that I’m adding to an iFrame:

<script>
    $('#list div').each(function(){
        $(this).append('<span class="togglebutton">Maximize</span>');   
    });

    $("span.togglebutton").click(function() {
        $(this).closest("li").children("div").toggleClass("maximized");
    });
</script>

How can I change the toggle between the text Maximize/Minimize when the toggleClass is maximized?

Answer by jondavidjohn

$("span.togglebutton").click(function() {
    var $this = $(this);  // cache jquerized 'this'
    $this.closest("li").children("div").toggleClass("maximized");

    var currentText = $this.text();

    // if the text is currently "Maximize"
    if (currentText === "Maximize") {
        // change it to new value
        $this.text("New Text");
    }
    else {
        // change it back to "Maximize"
        $this.text("Maximize");
    }
});

Answer by Starx

Well, if you are looking for some function like toogleClass() to do that job for you, you are out of luck. AFAIK, you have to do it manually.

Do something like this

function toggleText() {
    var curText = $("span.togglebutton").text();
    var newText;
    if(curText=="Maximize") { newText = "Minimize"; }
    else { newText = "Maximize"; }
    $("span.togglebutton").text(newText);
}

Now you can call it happily where you want to toggle it. Like

    $("span.togglebutton").click(function() {
        $(this).closest("li").children("div").toggleClass("maximized");
        toggleText();
    });
Read more
...

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