Oct 19, 2012

Centering image in the middle of the browser window with CSS

Recently I needed to center an image in the middle of the window browser, just to make a loading screen for a Phonegap app.

After googling for almost an hour and trying many ways, I just couldn't find the way to center it both vertically and horizontally. Finally , after reading this and trying many of the alternatives that the users have posted, it did the trick.

The CSS code to use is:

#yourimageid{
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

That's it, you don't need to put any more code in order to center your image! It will be always centered and in the middle of the browser, without any stretching applied.

I guess you can use it to center also a div in the middle of the screen, in case you need to put other stuff centered.

Oct 14, 2012

Disabling days in Magento calendar

Sometimes you need to modify the way Magento calendar works, so the user can't choose a holiday or a weekend day. This is not specifically explained by the Magento community or documentation, so I decided to post it here.

My version of Magento is 1.7, just to let you know, but should work with others.

Let's say you call your calendar via javascript like this:

    <script type="text/javascript">
        //<![CDATA[
        Calendar.setup({
            inputField: "sdate",
            ifFormat: "%Y-%m-%d",
            showsTime: false,
            button: "_dob_trig",
            align: "Bl",
            singleClick: true      
        });      
        //]]>
    </script>      

Then you get a functional calendar, but the user can choose any day of the year, and that's something we want to prevent.

So, what you have to do is to add a "disableFunc"  function to this calendar setup.

disableFunc: function(date) {
 //return true if you want the day disabled, false otherwise
 ...
}

For example, you could do something like this to disable sundays (remember, in javascript's Date object, Sunday is 0, Monday 1, ... until Saturday that is 6!


    <script type="text/javascript">
        //<![CDATA[
        Calendar.setup({
            inputField: "sdate",
            ifFormat: "%Y-%m-%d",
            showsTime: false,
            button: "_dob_trig",
            align: "Bl",
            singleClick: true,

            disableFunc: function(date) {
                  //disable all sundays and New Year day
                  var month = date.getMonth() + 1; //add 1 because January = 0 and so on
                  var day = date.getDate(); //get day number
                  if (month==1 && day == 1) return true;
                  return date.getDay() == 0;  //0 for sunday, 1 for monday, etc
            }
     });
     //]]>
     </script>

So the code above checks (the disableFunc is called for every day in the current month displayed by the calendar!) if the day is 1-1, if so, the day is disabled. Otherwise, it checks if the day is a Sunday, and if so, the day is also disabled.

Hope this code helps you out with calendar manipulation in Magento!
 

Oct 6, 2012

Phonegap + iScroll: solving keyboard issues

First of all, i must say that I'm using iScroll 4.2 with Phonegap 2.1 on an android project (eclipse), but this hack should work with other platforms and versions.

If you tried to click an input field (text box, select, etc) when using iScroll and phonegap, you will find out that you can't. That's because iScroll prevents the default behaviour of your click, making impossible to enter text or select anything.

I found the fix for this at Stack Overflow, however a new problem appears: the keyboard doesn't hide by itself when you put text inside the box!

To fix this, i hacked a bit the code from Stack Overflow. The final result is like this:

Step 1: change this code on iscroll.js :

    onBeforeScrollStart: function (e) { e.preventDefault(); },

and put this:

            onBeforeScrollStart: function (e) {
                var nodeType = e.explicitOriginalTarget ? e.explicitOriginalTarget.nodeName.toLowerCase():(e.target ? e.target.nodeName.toLowerCase():'');
               
                if(nodeType !='select' && nodeType !='option' && nodeType !='input' && nodeType!='textarea' && !showkey) {
                     e.preventDefault();    //prevents showing keyboard - scrolling
                }//otherwise, show keyboard, do default
                if(!showkey) showkey = true;
            },           

Then you must declare the variable "showkey" at the beginning of iscroll.js:

var showkey =true;

Then on your "onblur" events of your inputs you must put:

    <input onblur="showkey=false" .../>

So when you make onblur, the "e.preventDefault()" code can't be executed just one time, making default behaviour (hiding keyboard) possible.

Sep 23, 2012

Magento: URL Rewrite Disabled - How to force URL Rewrite



Yesterday I tried to make an URL rewrite or redirect in my local Magento 1.7. I just created a new category and needed it to redirect to the "log in" page.

So I just entered the backend, clicked Catalog -> URL Rewrite Management. The problem was, that the "Target Path" was disabled! So stupid that the Magento team disabled that...

EDIT: You can add Custom URL Rewrites and put any target and request paths if you create a new rule and set the type to "Custom". I recommend to delete the rules that may interfere with this first (system rules created by magento by default), then on URL Rewrite Management, press the Add URL Rewrite Button (upper right). Then on Create URL Rewrite set the value to "Custom". More info here. If you still have problems or want to change system URL rewrites, keep reading ;-)

After trying many approaches (like creating a block, a widget, etc) it was clear that the solution was to access the database directly with PHPMyAdmin and change values manually! So sad that it has to be like that, but well...

Here is the process to change the target path:

  1. You have to open your PHPMyAdmin or similar, then go to your Magento Database.
  2. There, look for a table called "core_url_rewrite".
  3. Browse it... then just look for your desired "request_path", that's the path that will be redirected. The one you want to modify is "target_path". Magento creates that value automatically, but now you can change it. The easy way is to press over it and change it manually.
  4. You are done!Go and test your cool URL Rewrite!!!

Hope it helps you out... :-)

Mar 7, 2012

Wordpress page as external link

Let's say you need a "Contact" page in your Wordpress but you don't want a page displayed. All you want is to open the email client with a "mailto" link. How to do that?

After digging on the web for some time i found this solution. You just have to create a blank page in your wordpress, and then put this in the title of the page:

<a href=”your-link”>The title</a>

So for example, if you want to open the mail client to your  email address, you should put a page title like:

<a href=”mailto:contact@mysite.com”>Contact</a>

And what if you want to point the link to another site?

<a href=”http://www.google.com”>Go to Google</a>

No plugins, no special tricks needed to put a link to a mail address or external link in your menu bar!

Thanks to Ulysses for the info.

Have fun!

Mar 5, 2012

Wordpress: Get page slug

So what if you need the page slug when programming on Wordpress? It doesn't have a function like "the_slug()". But no problem! You can put this code inside your "functions.php", located in your theme folder, and use it in your theme code!

function get_the_slug() {
    global $post;
    if ( is_single() || is_page() ) {
       
        return $post->post_name;        
    }else{
        return "";   
                  }   
}
You can use this function to generate a custom code for your page, according to the page you are in, like:

<?php
    if (get_the_slug()=="Contact"){
        echo "<span>Welcome to Contact section!</span>"
    }
?>
 BTW I got the code from the Wordpress codex (link here) , thanks to sligowaths for the code! I just tought that it would be nice to make it a bit more visible and show it's use.

Have fun!

Mar 2, 2012

Custom background gallery with Wordpress

Recently I had to make a Wordpress based site with a custom background. A friend of mine suggested using Wordpress gallery (via attaching the images to the pages) to do it. It's possible, and I have done it, however the actual site has to be moved, and i experienced some problems exporting and importing the posts and pages. The problem is, that when exporting, it gives some kind of error about the attached images.


So, i tried to find out another way to set background images for a Wordpress site, in a more easy and movable way. My purpose was to put all images on some sub-folder of the theme, and then use a custom field the page. This, combined with some magic code inside "functions.php" code, can make it possible.


Here are the steps!


1. Add a custom field to your pages. In my case, i called it "bgrange". (If you don't see custom fields it's because they are hidden, click "Screen options" upper right of the screen, for later Wordpress versions, after 3.2 i guess, then check "custom fields" check-box).


2. Put a value in the custom field. The code i made is able to recognize background ranges. Note that your backgrounds must be named with the same prefix and suffix, for example "my_background_XX.png", where XX is the number of the background. In the case of the image, the images selected are the named "my_background_01.png", "my_background_02.png",etc, until 8, and the final one is the image "my_background_19.png", in this case. Prefix and suffix can be set later to fit your preferences, as will be seen. Do this operation on all the pages that you want to show the custom background.


 3. Let's add some PHP code in your page header, for example.
<div id="preload" style="display:none;">
    <?php    
        $bgpath = "".get_bloginfo("template_directory")."/images/backgrounds/";
        $range = "".get_post_meta($post->ID, 'bgrange', true);
        echo "\n";
        get_backgrounds2($bgpath, "my_background_" ,".png", $range);
    ?>
</div>

Ok what this code does is: put a div with an ID called "preload" that is hidden, so images won't be displayed for now. Then, the php code gets the template directory of your theme, and supposes that your backgrounds are inside "<yourthemename>/images/backgrounds". You can change that to fit your needs. The second php line gets the custom field that we just added to the page. This is a string, that will be treated afterward. After that, a simple "echo \n" to ease the readness of the code (not necessary but makes easier to read your code). The final statement uses a custom function that has to be defined on your "functions.php", a file located in your theme folder in case you don't know, that includes a lot of functions used by your theme to make it work. So, the last step is to put these functions on functions.php file!

3. Open your functions.php file and put this code:

function get_backgrounds($path, $prefix, $sufix, $start, $end) {
    if($start<=$end){
        for($n=$start; $n<=$end; $n++){
            $nstr = trim("".$n);
            if($n<=9 && $n>=0){$nstr = "0".$nstr;}
            echo "<img class=\"bgimage\" src=\"".$path.$prefix.$nstr.$sufix."\"/>";
            echo "\n";
        }
        return true;
    }else{       
        for($n=$start; $n>=$end; $n=$n-1){
            $nstr = trim("".$n);
            if($n<=9 && $n>=0){$nstr = "0".$nstr;}
            echo "<img class=\"bgimage\" src=\"".$path.$prefix.$nstr.$sufix."\"/>";
            echo "\n";
        }
        return true;   
    }
    return false;
}

function get_backgrounds2($path, $prefix, $sufix, $list) {
    $data = explode(',', $list);
    for($n=0; $n<count($data); $n++){
        if(strpos($data[$n], '-') !== false){
            $rdata = explode('-', $data[$n]);
            get_backgrounds($path, $prefix, $sufix, $rdata[0], $rdata[1]);
        }else{       
            $nstr = trim("".$data[$n]);
            if(intval($data[$n])<=9 && intval($data[$n])>=0){$nstr = "0".$nstr;}
            echo "<img class=\"bgimage\" src=\"".$path.$prefix.$nstr.$sufix."\"/>";
            echo "\n";
        }
    }
    return true;
}


What makes this code? Ok, let's start by the second function. Basically what it makes is to get a path (the path to your backgrounds) a prefix (remember, "my_background_" for example), a suffix (".png" for example) and a list (that is, the custom field we added to our pages). The list is "exploded" into individual elements, separated by commas. Then, if a range of backgrounds is detected, the first function is called, that in turn explodes it and generates the list of images. If no range detected, the list elements generate individual backgrounds. You finally end up with a list of "<img>" elements "echoed" (that is, generated HTML put on your page). Since the <div> element that they are in is hidden, there is no problem. We just need that code in the page , so we can use it afterward.

So, now we have our page with a hidden div, and the images on it, they are not displayed but the code is there, now what?


4. Use a jQuery or JavaScript plug-in to show the images as backgrounds. I used successfully Supersized to do so. You just need to go to their page, i recommend you to check the demos and then download the source code. Then play with the downloaded demos locally, and check the code. It's really nice and easy to put it in your page. You will end up with a Javascript code like this:

<script type="text/javascript"> 
                var slidelist=[];
               
                function put_in(){
                    var x=$(this);
                    var source= ""+x.attr("src");
                    slidelist.push({'image': source});
                }
               
                var bgs = $(".bgimage");
                bgs.each(put_in);


The code above will let you put all the elements of a certain class, in this case ".bgimage" into a list. Get a look at the php code on functions php, and you will notice that this class is added to every image. So once you have the list, you can call the Supersized plug-in like this:

                $.supersized({ 
               
                    // Functionality
                    slide_interval          :   3000,        // Length between transitions
                    transition              :   1,             // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
                    transition_speed        :    700,        // Speed of transition
                                                              
                    // Components                           
                    slide_links                :    'blank',    // Individual links for each slide (Options: false, 'num', 'name', 'blank')
                    slides                     :      slidelist                   
                });
</script>

 I hope it helps you making your custom backgrounds easier and more movable, and without the long and boring process of attaching the images to your pages.

See you soon!