...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
August 30, 2010

Preloader with JQuery OR Advanced Page Load Behavior with jQuery Progress Bar

Question by Junaid Saeed

We have a jQuery Progress Bar. Is there a way we can have the progress bar displaying the loading of an HTML page which has PHP, CSS & JavaScript and all in it?

Like a preloader and when the page has been downloaded and rendered fully then display it.

If not with progress bar can we make a preloader with jQuery?

Answer by Starx

Once.. I tried to create this, but It was not pretty. I listed all the things I need to have on a page and increased the progress bar One by one as it was loaded. It was very tremendously long chain. Here is a sample of what I did.

$.getScript('js/lib/ui.js',function() { //Load the Jquery UI
    //Call back function after the loading is complete

    $("#progressinfo").html("Loading Widgets ..."); //Give the information 

    $.getScript('js/lib/widget.js',function() { // Load the jquery ui Widget
    //Call back function after the loading is complete

        $("#progressinfo").html("Loading Widgets: Progress Bar ..."); // Inform

        $.getScript('js/lib/widgets/progressbar.js',function() { // Finally load the Jquery UI progressbar
            //Call back function after the loading is complete

            $("#progressbar").progressbar({ value: 5 }); // change the value of the UI informing the total amount of loadding completion                                             
            $("#progressinfo").html("Loading Widgets: some script ..."); //Inform of another script

            $.getScript('somescript.js',function() { // Load another script
            //Call back function after the loading is complete

               $("#progressbar").progressbar({ value: 6 }); // change the value of the UI informing the total amount of loadding

            });
        });
    });    
});
Read more
August 28, 2010

Pure CSS Rounded Corners in IE6-8 (JQuery Accepted)

Question by BHare

There are a lot of JQuery plugins to give rounded corners to browsers that dont support CSS3. They either don’t work or have an ugly effect where you see it unstyled, and then the JS kicks in and finally makes them rounded.

I am looking for a solution that renders rounded corners before visibility, looking for a seamless, or near seamless solution.

The best match I have come to so far if the use of .htc files with www.css3pie.com. There is still that delay (Not sure if it can even be solved).

css3pie is around 26k compressed, the owner stated that if you have JQuery there could be scripts that would be less. (I plan on using JQuery throughout anyways).

Ideally, I’d like it to support gradients, border-radius, and box-shadow. Currently css3pie does all of this how I need, except for box-shadowing. It messes up if the background is transparent as indicated here: http://github.com/lojjic/PIE/issues#issue/12

I am willing to accept inability of any of these features in IE6.

I guess maybe I just can’t have one’s cake and eat it too. For now, I will be sticking with css3pie.com and putting up with annoying delay, and not allowing for box-shadow in IE. Not a huge deal because IE9 is suppose to fix that -crossing fingers-

Answer by Erik

The CSS3 PIE library handles a lot of things for IE6/7/8 including:

  • Border Radius (rounded corner)
  • Box Shadow
  • Border Image
  • Gradient Backgrounds

Its pretty handy.

Answer by Starx

Use jquery rounded corner plugin

http://jquery.malsup.com/corner/

And trigger the plugin in every possible events to ensure its loaded

<script>
   $(this).corner(); //This will trigger the function as soon as this line loads
   $(document).ready(function() { $(this).corner(); }); //not necessary
   $(window).load(function() { $(this).corner(); });//not necessary
</script>
Read more
August 27, 2010

PHP Get method not sending full input

Question by Jackass

I have a drop down list that is dynamically generated using a mySQL database using the following code:

$region = mysql_query("select region_name from region", $connection);

echo "<select name=region>Region</option>";

while ($row = $mysql_fetch_array($region))
{
  echo "<option value =$row[region_name]>$row[region_name]</option>";
}

echo "</select>"

This prints out the list perfectly fine however when I submit the form using the GET method any region name that has a space in it will not be passed through properly in the URL. Instead of “South Australia” it will only give me “South”

I know the URL should end up being:
http://foo.com/query.php?region=South+Australia

But instead the +Australia just doesn’t appear.

Anybody know what stupid stuff I’ve done or what I’m missing??

Answer by NAVEED

use single quote for value in option tag:

Try this in while loop:

echo "<option value='$row[region_name]'>$row[region_name]</option>";

Answer by Starx

There is an error in your code………

echo "<select name=region>Region</option>"; should be

echo "<select name='region'><option>Region</option>";

and while giving value do this

echo "<option value='$row[region_name]'>$row[region_name]</option>";
Read more
August 25, 2010

loading html page inside div

Question by coder247

how can I load an html page inside a div. With the ‘object’ tag it’s loading, but I think it’s not a good approach. It is not an external file. Is dojo good for this?

Answer by coder247

This also works… using dojo…

<script type="text/javascript">
var url = dojo.moduleUrl("dijit.form", "help.html");
dojo.xhrGet({
  url: url,
  load: function(html){
       dojo.byId("mycontent").innerHTML = html;
  }
});
</script>

<div id="mycontent">

</div>

Answer by Starx

Use jquery

$("#mydiv").load("myexternalfile.html");
Read more
August 24, 2010

description box on mouseover

Question by Артём Царионов

i am playing with the onmouseover event in javascript

i would like a little box to pop up and remain up until there is no onmouseover anymore

i think it’s called a decription box, but i am not sure?

how do i get a little box to pop up with custom text when i put my mouse over certain text>? and i need it to disappear once i move the mouse to a different object

Answer by casablanca

Assuming popup is the ID of your “description box”:

HTML

<div id="parent">
This is the main container.
<div id="popup" style="display: none">some text here</div>
</div>

JavaScript

var e = document.getElementById('parent');
e.onmouseover = function() {
  document.getElementById('popup').style.display = 'block';
}
e.onmouseout = function() {
  document.getElementById('popup').style.display = 'none';
}

Alternatively you can get rid of JavaScript entirely and do it just with CSS:

CSS

.parent .popup {
  display: none;
}

.parent:hover .popup {
  display: block;
}

Answer by Starx

Well, I made a simple two liner script for this, Its small and does what u want.

Check it
http://jsfiddle.net/9RxLM/

Its a jquery solution 😀

Read more
August 23, 2010

Always ensuring that div tag is at top of page using jquery

Question by Roland

I have a div tag <div id="customError">Error</div> I want this div tag to always appear at the top of the page using jquery, so with otherwords even if the page is scrollable I want it to be always visible and on top of the page almost like the stackoverflow notification bar. Is this possible using JQuery? I tried a number of things and it disappears when the page is scrolled down. Any help advise will be appreciated.

Answer by fantactuka

You can use css only:

#customError {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;

  /* IE6 */
  _position: absolute;
  _top: expression(document.getElementsByTagName("body")[0].scrollTop + "px");
}

Answer by Starx

use this

#customError { 
   position:fixed;
   top:0;
   left:0;
}
Read more

What happens if I don't call session_start()?

Question by Summer

I’m trying to make many of the pages in my site cache-able as HTML. As a result, I won’t be able to call session_start() on those pages. Do sessions work if you don’t call them on every single page?

Answer by WoLpH

If you don’t call session_start() than you won’t have $_SESSION available. But if the page is a static html file anyway than you won’t need $_SESSION for that page so you don’t have to worry about it.

You only need it on pages where you do something with $_SESSION

Answer by Starx

session_starts(), either starts the session, or allows you to use the session variables. If you want to start a session and store values there or you want to use the session values already there then, you must use session_start()

Do sessions work if you don’t call them on every single page?

NO

Read more
August 22, 2010

PHP secure root

Question by James

My friend found a problem in my script, it gives acces to root files.

This url gives passwd file:

http://site.com/attachment.php?file=../../../../../../etc/passwd

How to escape this security hole?

Answer by Your Common Sense

There are several different solutions.
If there can be only a filename, a basename() solution would work.

However, if it can be path, a more complex solution is needed

//assume current directory, but can be set anything. Absolute path of course
$basedir   = dirname(__FILE__);
//assume our files are below document root. 
//Otherwise use it's root dir instead of DOCUMENT_ROOT
$filename  = realpath($_SERVER['DOCUMENT_ROOT'].$_GET['file']);
if (substr($filename,0,strlen($basedir)) !== $basedir) {
  header ("HTTP/1.0 403 Forbidden"); 
  exit; 
}

there is also a useful PHP configuration option open_basedir

Answer by Starx

Dont download the files using URL String…. Define unique IDs to denote a file, rather than paths.

You might have seen downloads like this http://www.mysite.com/download.php?id=23423 what they do, use this id, to take out the file name and path from the db and then download it.

Read more

Help understanding PHP classes

Question by Sandro Antonucci

I’m trying to learn how to best use OOP in PHP. Please be aware that even if I studied the theory of this new “world” I didn’t enter the OOP thinking yet obviously.

What’s the difference between using normal, separated functions and putting them in a class as methods?

Let’s say I have a class called “shop”.

It has these methods: retrieveitems, deleteitems, updateitems, additems

Except for the fact that I can call methods inside methods with a simple “$this”, what is the difference between putting them in different functions without a class? I mean, for example, I still can call function deleteitems inside function retrieveitems right? Even if not in a class?

Please help me understand what I’m missing.

Answer by NullUserException

OOP provides, among other things, encapsulation.

class Shop {

    function __construct($items) {
        $this->inventory = $items;
    }

    function deleteItem($item) {
        $key = array_search($item, $this->inventory);
        if ($key !== false)
            unset($this->inventory[$key]);
    }

}

Now you can create instances:

$computerShop  = new Shop(array('ram', 'monitor', 'cpu', 'water'));
$hardwareStore = new Shop(array('hammer', 'screwdriver', 'water'));

And each one of them is independent from each other. If I do $computerShop->removeItem('water'), $hardwareStore should still have water in their inventory. (see it in action) Doing this the procedural way is much messier.


Another cool thing about OOP is that you can use inheritance and polymorphism:

class Animal {

    function eat() {
        $this->hungry = false;
    }

    abstract function speak();
}

class Cat extends Animal {

    function speak() {
        echo 'meow!';
    }
}

class Dog extends Animal {

    function speak() {
        echo 'woof!';
    }    
}

Now both Cat and Dogs can call the method eat() even though they are not explicitly declared in their classes – it’s been inherited from their parent class Animal. They also have a speak() method that does different things. Pretty neat, huh?

Wikipedia:

Object-oriented programming, Encapsulation, Inheritance, Polymorphism

Answer by Starx

One of the most interesting feature I like about classes are encapsulation. You can encapsulate various chains of function into one major function and call them directly. Encapsulation creates an environment where you can protect member objects and properties from being modified outside the class.

Another major part of Classes, is groups. To be able to group all the functions and attributes related to a particular object in one and the capability of making different instances of that classes as objects, is simply magical. Say you have a bunch of functions that refer to each other and pass around pretty much the same arguments. That’s a good sign that those functions belong in a class, and those arguments should be members of the class.

Since you are using PHP, imagine you have created a class which creates a panel. Now you can use this class and create different but similar layouts, like news panel, advertisement panel, product display panel by creating different objects of it, and supplying the content.

You might say this is also possible using functions, but functions cannot provide the scalability and flexibility the class provides.

Inheritance

This is one of the major feature of OOP, you can create parent and child classes to an infinite level. For example, you have created a class car. This class have attributes like wheels, gears, steering have methods like drive(), stop() but you can’t accompany every cars in this world, so now you will creates its child class. In this case, the child classes may be 2WD and 4WD, and again these child classes may also have other child classes with new members and methods. But you can access the members and functions all the way up to its parents, and grand parents.

Polymorphism

This denotes being able to override a function in parent classes. i.e the driving system of a simple car is different that the driving system of 4WD car, so you need to override the previous parent function and replace it with a new function.

Another is Overloading, its the ability to be able to use a function over different parameter cases. For example, for a simple car to drive, it needs engine starts, the gear and acceleration but for modern cars like ferrari, you only needs to start the engine and press the accelerator, you dont need gear, so for these two cases in order to use the method drive(), you supply different no of parameters. And classes make it possible.(But this feature is not available in PHP 🙁 )

Read more
August 21, 2010

what would be the proper way to add multiple functions to the jquery $(window).load function declaration?

Question by RandyMorris

I am using the following javascript to animate two slideshows using the nivo slider object in jquery:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>  
<script src="jquery.nivo.slider.pack.js" type="text/javascript"></script>  
<script type="text/javascript">  
$(window).load(function() {  
    $('#sliderone').nivoSlider({  
        effect:'fade',  
        slices:15,  
        animSpeed:500,  
        pauseTime:7000,  
        startSlide:0, //Set starting Slide (0 index)  
        directionNav:false, //Next & Prev  
        directionNavHide:true, //Only show on hover  
        controlNav:false, //1,2,3...  
        controlNavThumbs:false, //Use thumbnails for Control Nav  
        controlNavThumbsSearch: '.jpg', //Replace this with...  
        controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src  
        keyboardNav:false, //Use left & right arrows  
        pauseOnHover:true, //Stop animation while hovering  
        manualAdvance:false, //Force manual transitions  
        captionOpacity:0.8, //Universal caption opacity  
        beforeChange: function(){},  
        afterChange: function(){},  
        slideshowEnd: function(){} //Triggers after all slides have been shown  
    });  
});  
$(window).load(function() {  
    $('#slidertwo').nivoSlider({  
        effect:'fade',  
        slices:15,  
        animSpeed:500,  
        pauseTime:7000,  
        startSlide:0, //Set starting Slide (0 index)  
        directionNav:false, //Next & Prev  
        directionNavHide:true, //Only show on hover  
        controlNav:false, //1,2,3...  
        controlNavThumbs:false, //Use thumbnails for Control Nav  
        controlNavThumbsSearch: '.jpg', //Replace this with...  
        controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src  
        keyboardNav:false, //Use left & right arrows  
        pauseOnHover:true, //Stop animation while hovering  
        manualAdvance:false, //Force manual transitions  
        captionOpacity:0.8, //Universal caption opacity  
        beforeChange: function(){},  
        afterChange: function(){},  
        slideshowEnd: function(){} //Triggers after all slides have been shown  
    });  
});  
</script>    

This code works in internet explorer but not in chrome/firefox. I suspect it is because I am using the $(window).load(function() twice/incorrectly.

Any advice on how this can be properly done would be greatly appreciated.

Answer by Felix Kling

As the code of the both callbacks is nearly identical, I would refactor it to:

$(window).load(function() {  
    $('#sliderone, #slidertwo').nivoSlider({  
        effect:'fade',  
        slices:15,  
        animSpeed:500,  
        pauseTime:7000,  
        startSlide:0, //Set starting Slide (0 index)  
        directionNav:false, //Next & Prev  
        directionNavHide:true, //Only show on hover  
        controlNav:false, //1,2,3...  
        controlNavThumbs:false, //Use thumbnails for Control Nav  
        controlNavThumbsSearch: '.jpg', //Replace this with...  
        controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src  
        keyboardNav:false, //Use left & right arrows  
        pauseOnHover:true, //Stop animation while hovering  
        manualAdvance:false, //Force manual transitions  
        captionOpacity:0.8, //Universal caption opacity  
        beforeChange: function(){},  
        afterChange: function(){},  
        slideshowEnd: function(){} //Triggers after all slides have been shown  
    });  
});

Also consider to use the document ready event instead: $(document).ready(function(){...}) or short $(function(){...}).

Starx mentioned to use a class instead of IDs, which is also a good advice!


Assuming that both sliders should look and work exactly the same, this code makes it way more easier to make changes to them, as you only have make the change once (increases maintainability and readability).

Answer by Starx

Try using class instead of id. Looks likes all the options are same so you dont need to use the same code twice. Try using class and queuing up multiple window.load function dont create any trouble

Like this

$(window).load(function() {  
    $('.sliders').nivoSlider({  
        effect:'fade',  
        slices:15,  
        animSpeed:500,  
        pauseTime:7000,  
        startSlide:0, //Set starting Slide (0 index)  
        directionNav:false, //Next & Prev  
        directionNavHide:true, //Only show on hover  
        controlNav:false, //1,2,3...  
        controlNavThumbs:false, //Use thumbnails for Control Nav  
        controlNavThumbsSearch: '.jpg', //Replace this with...  
        controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src  
        keyboardNav:false, //Use left & right arrows  
        pauseOnHover:true, //Stop animation while hovering  
        manualAdvance:false, //Force manual transitions  
        captionOpacity:0.8, //Universal caption opacity  
        beforeChange: function(){},  
        afterChange: function(){},  
        slideshowEnd: function(){} //Triggers after all slides have been shown  
    });  
}); 

Now give both yours sliders class sliders

Read more
...

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