Solution for jQuery Cycle’s scrollHorz property hiding slides

There are two ways to slide easily through life: to believe everything or to doubt everything. Both ways save us from thinking.
-Alfred Korzybski

This is more of a reminder for me than anything else. If it helps you then thats an added advantage ;)

I ve been building the Instant Customer system for some time now and it has a lot of z-index’s all over the page for the various overlapping effects we have in there. The last z-index I set had me look up for the max z-index that you can possibly set and it happens to be unlimited but most browsers will limit it to signed 32 bit values, so 2147483647 is the max you should reach. Obviously I m not using that many indices on Instant Customer, but there are at least a 100s of em set arbitrarily from tens to tens of thousands. So anyway, all this messes up the z-index that jQuery Cycle plugin sets for slideshows. The most noticeable (to me) was the slide type ‘scrollHorz’ not displaying any of the slides at all but functioning nevertheless. I switched the one’s using ‘scrollHorz’ to ‘fade’ and they worked! But then some slideshows necessarily required the scrolling feature, especially in the Tips section of Instant Customer on the bottom.

The solution that popped up after experimenting a bit inside Firebug was to set a fixed height on the parent div/html element of the slideshow holders. It can even be a min-height.


Categories: jQuery, Tips | Leave a comment

Javascript equivalent for PHP’s array_map()

To map out a course of action and follow it to an end requires courage
Ralph Waldo Emerson

I was looking for an equivalent of the PHP array_map() function or the Python map() function in Javascript.  Turns out that Javascript doesnt have this natively but sure enough jQuery has one!

function sq(x) { console.log(x*x); }
//call the following in document.ready
$.map([1,2,3,4,5], sq);

This returns:

1
4
9
16
25

Another way for doing this without jQuery is to use the following function. It is based on a function I found in a wonderful book on Javascript  called Eloquent JavaScript: A Modern Introduction to Programming that I am currently reading (a free online version is available on the book’s site),

function map(func, array) {
    var len = array.length, result = new Array(len);
    for (var i = 0; i < len; i++)
    result[i] = eval(func + "(" + array[i] + ")");
    return result;
}

In the book, the author uses the function argument(func) without eval() like this,

result[i] = func(array[i]);

I changed that bit.


Categories: Javascript, jQuery, Tips | 1 comment

How to split an array into smaller arrays

“The soul can split the sky in two and let the face of God shine through.”
-Edna St. Vincent Millay

Some days ago I need to split an array into multiple smaller arrays. I m not sure if this is the perfect way to do it, but here is anyway. If you know a better way by maybe using Array.splice() or something then please lemme know via comments.

var arrToSplit = ["won", "to", "tree", "foe", "five"];
var itemsPerSmallerArr = 3;
var distributedArr = [];
var count = 0;
var tmpArr = [];

for(i=0; i < arrToSplit.length; i++){
    if(count < itemsPerSmallerArr)
    {
        tmpArr.push(arrToSplit[i]);
    }
    else
    {
        distributedArr.push(tmpArr);
        count = 0;
        tmpArr = [];
        tmpArr.push(arrToSplit[i]);
    }
    count++;
};

distributedArr.push(tmpArr);
console.log(distributedArr);


Categories: How To, Javascript | Tags: | Leave a comment

How to find and replace in multiple files from the terminal

You have to kiss a few frogs before you find a prince.
-Anonymous

There are times when you d like to search for a word/phrase/regular expression in a number of files together and optionally replace it with something else. If you do not use a IDE then you may need to deploy the terminal to do this. In a terminal, change directory(cd) to the directory where you want to ‘find and replace’ and

grep -lr -e '<oldword>' * | xargs sed -i 's/<oldword>/<newword>/g'

This will work on a Mac as well.

Explanation

  • grep is a command line text search utility
  • -l get the files with matches
  • -r recursiveget a list of all matched files
  • -e stands for the PATTERN to match
  • xargs will will return the matched files as arguments
  • sed is th Unix stream editor utility
  • -i edit files in place

Reference (not man pages)


Categories: How To | Tags: , | Leave a comment

How to replace multiple instances of a string in Javascript

If you don’t like something change it; if you can’t change it, change the way you think about it.
-Mary Engelbreit


You can use String.replace(/oldstring/g, “new string”); to replace multiple instances of a string but what if you did not know the exact word that you needed to replace? Also it is a word that is inside a variable. For example, I was recently replacing a bunch of words that were in the format:

%var%

The ‘var’ was  a variable in a for loop. So if I tried to use:

String.replace("%" + var + "%", "newword");

This would work only on the first match. The following wont work either coz the contents inside the 2 forward slashes are considered as the actual string to replace.

  • String.replace(/"%" + var + "%"/g, "newword");
  • String.replace(/%var %/g, "newword");

So here s what can be done(and it works):

$var = new RegExp("%"+var+"%", "g");
String.replace($var, "new value");


Categories: How To, Tips | Tags: | Leave a comment

Making HTML tags more useful by custom attributes

Being good is commendable, but only when it is combined with doing good is it useful.
-Anonymous


I have been over using a simple technique to pass on more data to an HTML element in order to manipulate it better using jQuery. What I do is, I add as many custom attributes to an element and later retrieve them like this

$(element).attr(customAttribute);

So if I wanted to show or hide particular div s on the click of a checkbox, I d first write the HTML like this:

<input type="checkbox" div2toggle="div1"  />
<input type="checkbox"div2toggle="div2" />
<input type="checkbox"div2toggle="div3" />
<input type="checkbox"div2toggle="div4" />
<div id="div1">Content for div 1</div>
<div id="div2">Content for div 2</div>
<div id="div3">Content for div 3</div>
<div id="div4">Content for div 4</div>

And then I d put the following inside $(document).ready(); or wherever

$(document).ready(function(){
    $(":checkbox").change(function(){
        $($(this).attr("div2toggle")).toggle();
    });
});

Using this technique will help you create tabbed content, non-form based input elements, auto hiding content on checkboxes or radio buttons and much more. Saves quite a bunch of lines of code!


Categories: jQuery, Tips | 2 comments

How to quickly create iPhone style on off buttons

Whenever you’re pissed off, just remember that it’s better than being pissed on.
-Christopher Titus

The famous iPhone on off style sliding buttons can be quickly created by using jQuery and jQueryUI draggable behavior. Here’s quick demo if you’d like to see what we are going to create. You ll need the following to get started with this:

  • jQuery Javascript Library (click to download version 1.6.1)
  • jQueryUI custom build with draggable behavior (create a custom build by first deselecting all the components and then selecting draggable. The required components will be selected automatically)
  • A background graphic for the iPhone style button
  • A png graphic for the slider

You can create your own version of graphics as well. I just wanted to create a slight variation than the original iPhone version. So here are 2 graphics that you can use for this tutorial:

CSS
The CSS for the button is straightforward. The is a container div (the background graphic) and inside this div is another div with the slider graphic (png).

<style>
.cb-bg
{
    width: 80px;
    height: 26px;
    background-image: url(your/path/to/images/cb-bg.gif);
}

.cb-slider
{
    width: 39px;
    height: 26px;
    background-image: url(your/path/to/images/cb-slider.png);
    cursor: pointer;
    position: relative;
}

</style>

Make sure you enter the relevant path to your images folder. Also the width and height  pertain to the graphics I have provided here. If you create your own graphics then make sure you update the dimensions in the stylesheet accordingly.

HTML

<div class="cb-bg">
    <div class="cb-slider" cb-status="0"></div>
</div>

As you can notice, I ve added an extra attribute to the inner DIV and called it cb-status. This is a neat way to add some more ‘value’ to your HTML tags by simply adding your own custom attributes. The HTML tag doesnt care what you call it. Its just like an attribute you’d create in an XML node. I add custom attributes to HTML tags a lot. It helps me to pass on a lot more information that I can later use and manipulate.

jQuery
Make sure you have added the <script> tags to load jQuery and jQueryUI custom build JS files in the <head> area of your HTML.

<script src="path/to/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="path/to/jquery-ui-1.8.13.custom.min.js" type="text/javascript"></script>

I generally make a JS file called document.ready.js to put in jQuery init code though its not really required for this particular tutorial. So in your <head> content add another ‘script’ tag and stick in the following code:

<script type="text/javascript">

$(document).ready(function(){
    initCheckBoxes();
});

var slideSpeed = 150;
var leftDist = 41;

function initCheckBoxes()
{
    $( ".cb-slider" ).draggable({containment: "parent"});
    $(".cb-slider").mouseup(function(){

    var status = $(this).attr("cb-status");

    switch(status)
    {
        case "0":
        //its off, slide it by 41px;
        $(this).animate({left: leftDist}, slideSpeed);
        //change status to 1
        $(this).attr("cb-status", "1");
        break;

        case "1":
        //its 'on', slide it to 0px;
        $(this).animate({left: "0"}, slideSpeed);
        //change status to 0
        $(this).attr("cb-status", "0");

        break;
    }
    });
}

</script>

In this code, the variable leftDist is basically the distance the slider will move away from the left. The value for this may change if you create your own graphics. Make sure you update this value in that case.

And that’s it! You can check out a demo on this page.

Ideally I would have the stylesheet rules in its own CSS file and the initCheckBoxes() function along with the 2 variables in a JS file called checkbox.js. I have put everything one page in this tutorial only to demonstrate how you can quickly create iPhone style sliding on-off buttons. You can use this instead of regular HTML checkbox. You ll just need to scrape out the value of the cb-status attribute and put it in a hidden field. You wont need to do that if you are using jQuery based ajax, where you could directly put the value in a post variable.


Categories: How To, jQuery | Tags: | 3 comments

Vimeo’s embed code doesn’t go well with jQuery

Ain’t no fool like an old fool
-Anonymous

If you are using some jQuery to load a page with the latest Vimeo embed code then there are chances it ll throw out this error:

Permission denied for <http://player.vimeo.com> to get property Location.toString

There is nothing wrong with jQuery and we’ll just have to wait till Vimeo fixes the embed code from their site. In the mean time though, you could just use the old embed code which is available when you chose the Embed option of a video. Of course then it may not work on an iPad.


Categories: jQuery | Tags: | 1 comment

How to disable dragging on a HTML element with jQuery

They are not free who drag their chains after them.
-French proverb

All HTML elements have a default nature whereby they can be dragged around for whatever reasons. Sometimes you dont want this, especially on sliders. Of course, if you the jQueryUI slider plugin then you don’t need to do this. But using the slider plugin just to stop dragging is overkill. Instead, add a class to each of the elements that shouldn’t drag, maybe “undraggable” and then use jQuery to return false on its mousemove event.

$( ".undraggable" ).mousedown(function(){return false;});


Categories: How To, jQuery | Tags: | Leave a comment

How to enable custom thumbnails in WordPress

“Anyone who doesn’t take truth seriously in small matters cannot be trusted in large ones either.”
-Albert Einstein

 

If you need to set your own custom thumbnail size for your thumbs then in your custom theme folder’s functions.php file paste the following:

if ( function_exists( 'add_theme_support' ) ) {
    add_theme_support( 'post-thumbnails' );
    set_post_thumbnail_size( 180, 180, true ); // default Post Thumbnail dimensions (cropped)
    add_image_size( 'category-thumb', 300, 9999 ); //For creating additional image sizes - 9999 signifies any height
}

If you have already added posts to your blog, then you ll want to affect all the thumbnails that have already been created. In that case, go here and download the AJAX Thumbnail Rebuild plugin and stick it in your plugins folder.

Activate the plugin.
Go to Tools and click Rebuild Thumbnails. Here you should see your newly added post-thumbnail directive after the default ‘thumbnail’, ‘medium’, ‘large’. I chose to rebuild only the last one as opposed to the others.

Click Regenerate All Thumbnails.

Once thats done, you can style the newly created thumbnails by styling the img.wp-post-image in your style.css file. More info here.


Categories: How To, Wordpress | Tags: | Leave a comment

← Older posts

Newer posts →