October 29, 2012

Animate/Ease an element to position when other elements disappear

Question by Jonathan

Please take a look at this fiddle: http://jsfiddle.net/dhcyA/

Try clicking on a block. What I want is that when the other elements disapear, the selected block will animate/ease to his giving position instead of just jumping like it does now. Then the same animation repeats itself when clicking again on the box, but then back to place.

Maybe to keep in mind:
I’m using a reponsive design, which means those blocks can be vertical and horizontal after scaling the window.

Any redevisions on the fiddle or suggustions would be great!

Answer by Starx

Here is my solution & features it offers:

  • Remembers the last position and gradually animate to/from this position
  • Block positions are calculated and animated on load and every resize
  • Repositioning happens on $(window).resize() thus maintaining the fluid nature of the block, despite the use of position absolute
  • Support variable heights
  • Minor change on existing markup & CSS

On your existing markup, I added a wrapper division.

<div id="wrapper">
    <div class="block">
        <h2>I'm block 1</h2>
    </div>
    ....
</div>

To maintain the fluidness of the block, I created a function to position the block on the wrapper. Here is the function for position of the blocks:

var reposition = function() {
    wrapper = $("#wrapper");
    pLeft = 0; //The starting point of all repositioning
    pTop = 0;

    maxRowHeight = 0;

    $(".block").each(function(){
        $(this).stop(0,0).animate({
          'top' : pTop + 'px',
          'left' : pLeft + 'px'
        });

        pLeft += $(this).width(); //Add the left position for next block

        if($(this).height() > maxRowHeight) maxRowHeight = $(this).height(); //Find out the longest block on the row

        //If the next block will exceed the width of the wrapper
        if(pLeft + $(this).next().width() >= wrapper.innerWidth()) {
           pLeft = 0; //reset the left
           pTop += maxRowHeight;
           maxRowHeight = 0; 
        }
    });    
};

Finally, the script to toggle the block

$(".block").click(function() {

    $(this).siblings().slideToggle('slow'); //Toggle other blocks

    if(!$(this).data('active')){ //if the block is not active
        $(this).data('left', $(this).position().left); //sets its left
        $(this).data('top', $(this).position().top);   // and top position
        $(this).animate({ //animate at the top and bottom
            top:0,
            left:0
        },'slow');

        $(this).data('active',true);

    }else{

        $(this).animate({ //animate to its last known position
            top:$(this).data('top'),
            left:$(this).data('left')
        },'slow');

        $(this).data('active',false);
    }
});

Demos

  • Demo[Full] (Resize this to see the fluidness maintained)
  • Demo[Full] (version supporting variable heights)
October 28, 2012

Why couldn't I call eval() in this way?

Question by warl0ck

Why is the following code fails to compile:

<?php
  $str = "echo "ok"";
  $func = "eval";
  $func ($str);
?>

And php tells me eval was undefined.

Answer by Boann

In PHP, eval is a “language construct”, not a function. (Notice It turns keyword-color in syntax highlighting editors.) Language constructs cannot be called using the variable function syntax $func() or used with other function-specific things like is_callable().

From http://www.php.net/manual/en/functions.variable-functions.php:

Variable functions won’t work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

Answer by Starx

eval() cannot be called using a variable function. If you don’t understand what a variable function is? look at the following part of your code

  $func = "eval";
  $func ($str); //Here $func becomes eval upon execution making it a variable function

If you look at the manual reference, its clearly noted

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

Suggestions with pagination

Question by dorin dorin

I’ve a problem with pagination. The php code of pagination query is:

$ <? if (isset($_GET["page"])) { 

    $Page = preg_replace("/[^0-9]/","", $_GET["page"]);
} else {
    $Page = 0;
}
$limit       = 10;
$StartFrom  = $limit * $Page;
$TotalFiles = mysql_num_rows(mysql_query("SELECT * FROM linkuri WHERE `categorie` = 'Afaceri' AND status = 1"));
$TotalPages = floor($TotalFiles / $limit); ?>

And code to display it:

$i = 0; while ($TotalPages >= $i) { echo '<a class="active imgf" style="opacity: 1;margin-bottom:3px; margin-top:3px;" href="afaceri.php?page='.$i.'">'.($i+1).'</a>';$i++;}

The problem is I am trying to make the display as: PAGES: "BACK" 1 2 3 4 5 "NEXT"

Answer by Starx

First I would like to suggest an improvement on your query. To count the total rows use:

SELECT count(*) as `totalpost` FROM linkuri WHERE `categorie` = 'Afaceri' AND status = 1

Then, you are create that pagination by doing something like this:

$totalPost = 50; //Dummy total post
$limit = 10;

$pages = $totalPost / $limit; //Giving 5

//Now we know there are five pages
for($i=1; $i<=$pages; $i++) {
  echo $i; // Better echo something like <a href="link">$i</a>
}

P.S: This is a very basic example

After you get the hang of how to create the pagination effect, check this tutorial

How to paginate with PHP?

Is there a Javascript library to go from geopoint and time to timezone?

Question by Luke Hoersten

I’m looking for a Javascript library that can take a geopoint and date and return the timezone. The date is used as input in order to determine the daylight savings time status for that date and location.

I’ve seen there are services which make this information available:

The information is mostly static, though, so I’d like to not have to depend on external services and am therefore looking for a library. Here’s an example of how I’d like it to work:

tz = geodate.timezone(someFutureDate, lat, lng) => TimeZoneObject
tz.abbr() => "CST"

Answer by Starx

Finding the time zone based on the latitude and longitude has been previously asked on this community. Check

  1. Determine timezone from latitude/longitude without using web services like Geonames.org
  2. Get PHP Timezone Name from Latitude and Longitude? (Similar to 1)

Quoting an answer from Michael

  • Download the database of cities from geonames.org
  • convert it to a compact lat/lon -> timezone list
  • Use an R-Tree implementation to efficiently lookup the nearest city (or rather, its timezone) to a given coordinate

Now, answering the JavaScript part, JS alone cannot perform such queries as it runs on Client’s Machine. SO either you have to create an API to query the results or send AJAX request to a server page returning you the results.

Sending AJAX request would be a lot better and easier.

How to put a function inside an object and directly output the result

Question by Dan Myasnikov

Look, I ve got the following code to be executed and the result expected:

a = { a: function(){ return 'red'} }

so whenever I call

a.a #=> I would like to receive 'red' rather than 'function(){ return 'red'}

Any help appreciated

Answer by Starx

Simply do this

a = { 
   a: 'red' 
};

But if having the result return function that important, we have to make sure the function get called and returned.

a = {
    a: function() {
        return 'red-by-function';
    }() //This will ensure the function is called rather that returning the whole function
};

Demo of both cases

Scroll a 100% height div over top of main content area while scrolling?

Question by Dustin McGrew

What I’m trying to do is a little hard to explain. I want to have a “panel” that would be 100% of the window height and is overlaid on top of the main content of the website. What I want to happen is to have the main website content locked to the top of the browser window and have this “panel” over top of it. This part is easy just using z-index. The problem I’m having is getting the main content of the site to stay fixed at the top of the browser window and when the user scrolls down only the “panel” slides up to reveal the main part of the website below it. Once the panel has cleared the top of the browser window I want the main part of the site to scroll as usual. I would like this to be driven by jQuery.

Here’s the HTML I have:

This is an overlay that needs to slide over top of the main content when the user scrolls down.

This is the main content of the website.

And some CSS:

html, body {height:100%;}

.panel {height:100%; background-color: rgba(186,85,85,0.38); position: relative; z-index:1;}

.main {position: absolute; top:0px; min-height: 1500px;}

EDIT: Think of this effect like a curtain rising on a stage. The stage stays in place while the curtain rises.

Answer by Starx

Viewing this problem from overly simple point of view, using position: fixed can fix the main content website while others scroll.

October 27, 2012

How to solve a session expiration issue

Question by user1295167

I am doing a site which has a problem with session expire issue. The form contain almost 50 input fields , I have done it in ajax. I have given the user checkings in page reload the problem is that session and cookies are setting is done when page reloads,

How can I check whether user logined or not without lossing data? Is there any ajax functions
to retain session?

Answer by Starx

One way of solving this would be to increase the session timeout.

ini_set('session.gc_maxlifetime', '3600'); //Assign the time in seconds

Custom Number format and images in between

Question by Maarten Hartman

I’d like to format a number(stored as 10000.23, or 1.23) with php, , and place images between them, like the following.

10000,23

becomes

[img1]100[img2]00[img3]10

and

1,10

becomes

[img1]0[img2]1[img3]10

Anyone knows how to do this?

I tried several number formats but none of them allowed me to separate the last 4 digits into two pairs ( 00.00.00 )

Answer by Starx

Looks as if you want currency Format and replace the quotation marks with images. Here is a small function to add commas on the number.

function cFormat($number) {
    while (true) {
        $replaced = preg_replace('/(-?d+)(ddd)/', '$1,$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } else {
            break;
        }
    }
    return $number;
}

Then, here is how to replace them with images.

$int = 10000.23;
$int = cFormat($int);

// After adding comma, use str_replace() to replace comma with images
$int = str_replace(",", "<img src="comma.jpg" />", $int);
$int = str_replace(".", "<img src="period.jpg" />", $int);

how to get integer value from textfield and retrieve the value to another class in java

Question by user1778569

How to get integer value from textfield and retrieve the value to another class in java ??

I know how to get but if i used in another class he get me 0 value,,,

“this is in the GUI” x1,x2,y1,y2 predefined

private void X2_accesActionPerformed(java.awt.event.ActionEvent evt){              
     x2=(int)(Double.parseDouble(X2_acces.getText())); 
}

I want to draw line the user inter 2 point (x1,y1) and (x2,y2) after that move the value to class draw line

“this is in class drawLine”

Next_frame nf=new Next_frame();
Point2D.Double p2=new Point2D.Double(nf.x2,nf.y2);

Answer by Starx

The following statement is quite ambigous.

x2=(int)(Double.parseDouble(X2_acces.getText())); 

You are parsing the value as Double and casting it down to int. This is enough:

x2 = Integer.parseInt(x2_acces.getTest());

Now, when passing this value to another class, you have to make sure, that the method to which you are passing to accept the data type you are about to send.

For example:

For a class like this:

class DummyClass {
   public DummyClass(int X) {
      //Here note that 'x' is asking for a integer so you have to provide it with integer
   }
}

Then you have use them in the following order:

x2 = Integer.parseInt(x2_acces.getTest());
DummyClass c = new DummyClass(x2);
October 26, 2012

Jquery – Creating a general language file to declare defaults for any plugins

Question by denislexic

Like most people, I use a bunch of jquery plugins on my website. From Twitter bootstrap to jquery ui datepicker and so on.

But I need my website to be multilingual, so I created a general language file called english.js , and in that file I want to declare some of the defaults from plugins as well as other language variables.

The problem is that all these plugins have varying structures to declare defaults. I saw a couple of questions already ( jquery – setting plugin defaults?, Globally defining jQuery plugin parameters , jQuery plugin defaults , …). But they are not clear.

STRUCTURE 1

$.fn.ajaxStatus = function (params)
{
    var settings = $.extend(
            {
                defaultLoadingText :"Loading...",
                defaultSavingText  :"Saving...",
                defaultDoneText    :"Done",
                defaultRedirectText:"Redirecting...",
                defaultErrorText   :"Oops! Our bad, something wrong.";
            },$.fn.ajaxStatus.defaults,
            params),
});

STRUCTURE 2

   jQuery.fn.extend({
        shrinker:function (options) {
            var opts = $.extend({
                "moreText":"Read more", 
                "lessText":"hide",
            }, $.fn.shrinker.defaults, options);
   });

THE QUESTION

Without modifying the plugin, is it possible to assign some defaults for the function that will be used every time I use the plugin?
How can I define the language defaults in an external file?

Right now, I have this in my language file, but it feels wrong, is this how you do it?

if ($.fn.ajaxStatus !== undefined) {
    $.fn.ajaxStatus.defaults =
    {
        defaultLoadingText :"Loading2...",
        defaultSavingText  :"Saving2...",
        defaultDoneText    :"Done2",
        defaultRedirectText:"Redirecting2...",
        defaultErrorText   :"Oops! Our bad, something wrong"
    };
}

Thanks in advance for you help.

Answer by Starx

I have done somehow similar to this. But I am not giving the full implementation.

Here is how to do it.

Define your plugins params for language like this:

var options = {
    lang: "np" //your default language
};

Set up your language objects like this

var lang = {
    "en": {
        "var1" : "This is variable one"
    },
    "np": {
        "var1": "यो एउटा भेरियबल हो ।"  //Different text based on language initials
    }
};

Then you can simply create a function to read the value like this

function showVar1() {
    alert(lang[options.lang].var1);
}

[Demo]Its not a plugin based.

...

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