Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Wednesday, March 28, 2012

Floating Section Scrolls with Page (HTML & JS)

I had the need yesterday to make a section or block of HTML scroll with the page. I wanted it to stay in a spot on the page, relative to all else, until the visitor scrolled the page down. Then I wanted it to stay at the top of the page, never scrolling off the page. It was to be a section (eg, a navigation bar or image) that essentially had an initial "parked" position in the design, but should always be visible, even when the user scrolls down. Check out the illustration to the right and an example of the code in use.

I've seen different implementations of this. The most popular solution is a "chaser" where the element's absolute position is updated dynamically after each page scroll event. You have probably seen sites like this. They are a bit annoying and clunky - the element is constantly hiding and showing after every scroll.

After no luck finding a solution that I liked, I created one. It is below for your enjoyment. It uses jQuery to make things easier (ie, this framework is required). Take, use and be merry.

AND, the javascript:

$(function() {
 
 window.floater = {};
 
 /* Settings */
 window.floater.element = $('#float'); // Element to float
 window.floater.topMargin = 20; // Margin from top of window
 
 /* Global Vars & Initial Position */
 window.floater.captured = false;
 window.floater.posi = window.floater.element.offset();
 window.floater.marginLeft = parseInt(window.floater.element.css('margin-left').replace('px', ''), 10);
 
 $(window).scroll(function() {
  var curScroll = {
   top: $(window).scrollTop(),
   left: $(window).scrollLeft()
  };
  
  if (curScroll.top >= (window.floater.posi.top - window.floater.topMargin)) {
   
   if (!window.floater.captured) {
    window.floater.captured = true;
    var scrollAtTrigger = curScroll.top;
    if ((window.floater.posi.top - scrollAtTrigger) < window.floater.topMargin) scrollAtTrigger = window.floater.posi.top - window.floater.topMargin;
   }
   
   window.floater.element
    .css({
     position: 'fixed',
     top: (window.floater.posi.top - scrollAtTrigger)+'px',
     left: (window.floater.posi.left - window.floater.marginLeft - curScroll.left)+'px'
    });
    
  } else {
   
   window.floater.captured = false;
   window.floater.element.css({ position: 'static' });
   
  }
 });
 
 $(window).resize(function() {
  var posiFix = window.floater.element.css({position: 'static'}).offset();
  window.floater.element.css({position: 'fixed'});
  window.floater.posi.left = posiFix.left;
  $(window).scroll();
 });
 
});

The nuts and bolts: Put the float wherever you'd like it to be on the page initially. Then, when the document is loaded, the JavaScript goes to work. It sets up two events: one page-scroll event and one page-resize event. This is where the hard work is done. Once the page scrolls past a certain point, the position of the floater is set to fixed which means it remains a certain position relative to the window or viewport. There is no flickering or chasing using this method. It is clean and smooth.

Note: The floater's initial CSS position must be set as 'static' (which is a CSS default if it is undeclared). If you need to set it to 'relative' or 'absolute', use a wrapper to position it.

Note 2: I've noticed on Firefox 6.0 that there is a weird bug (?) that causes iframes to refresh if their positioning switches from 'static' to 'fixed'. So, if you plan on playing a YouTube video in your floater, beware: it my refresh and reset your video on scroll.

Wednesday, January 25, 2012

jQuery UI & Disabling Text Selection on Click

Part of making a wonderfully interactive website with jQuery is the process of making certain elements clickable. Sometimes that means making a portion of text interactive without using the regular means of a hyperlink. One problem comes up when doing this, however. When a person clicks rapidly the browser usually interprets this to mean you want to highlight a word or paragraph. How do you stop this? Call .disableSelection() on the element with jQuery. This will disable text selection. For example:
$('#elementId').disableSelection();
It actually binds an event on the object which prevents the default behavior. It is an undocumented feature but it is awfully handy. Remember: it requires jQuery and jQuery UI as it is part of the jQuery UI core.

Friday, January 13, 2012

Synchronous AJAX with JQuery

Yes, you read that right. I just didn't think anyone would understand SJAX.

AJAX, if you don't know, stands for Asynchronous JavaScript and XML and is the term widely applied to sending HTTP POST and GET requests from client-side javascript. In JQuery, that would be $.ajax() or $.getJSON() or any one of the other similar variations.

The question that I had, to continue with the topic of this post, was, How do I do preform a synchronous AJAX call? That is, how would I treat an AJAX call as if it were inline javascript. The JQuery functions I mention above have a parameter where you would specify the call-back function that would run after the requested document is fully retrieved by the client, hence the response and call back are run asynchronously, or whenever the response has been received from the server. Then, how do I make this synchronous so that the code after the call does not execute until the javascript GET or POST is complete.

Well, it is pretty darn easy, I've found. There is a single parameter, "async," that you set to false. That's it. I've written this whole blog post and the answer is a one-word parameter: async.

$.ajax(ajaxurl, {
     async: false
});

So, now you know how to do SJAX. ;)

Thursday, December 1, 2011

Web App Framework Review: Sencha Touch, jQuery Mobile & more

I was recently evaluating the different frameworks for developing mobile web apps. I created an app in Sencha Touch, jQuery Mobile and JQTouch.(I also did a responsive web site using media queries, but this isn't so much a framework.) Here is my summary.

Sencha Touch is very different than anything I have used before. All of the content of the web app is built with JS. You code everything with JS. This causes things to be a bit janky, especially on older smart phones that need more time to process all that script. The biggest drawback, however, is that the online documentation is very difficult to use, especially for newbies. They have a few video tutorials online, but some are outdated and many are inconsistent (some use MVC architecture, for instance, which really throws you off if every other tutorial doesn't). All-in-all, if you are a web developer by trade and are used to manipulating DOM-level elements, this is a very frustrating framework to try to learn. Be ready to spend a serious amount of time on the learning curve. (Also, you have to pay Sencha if you want the latest and greatest version of their framework.) After attempting a few different projects with Sencha Touch over months, I grew frustrated and threw in the towel, even outsourcing the remainder of one project to India.

jQuery Mobile is well documented and has plenty of example code for you to follow along. You develop your web app as you would a website and use different data-xxxx attributes on HTML objects to describe how objects should be styled or used. Once you have your structure, jQuery Mobile takes care of the rest, making everything look nice and employing fancy animated screen transitions. There is a small learning curve when getting started, nothing compared to Sencha Touch. And last but not least, jQuery Mobile is FOSS and appears to be in very active development. I was very happy with the example projects I put together with jQuery Mobile. They were easy to finish and worked well.

JQTouch, when I evaluated it, didn't appear to be in active development. The documentation was a little sketch and I found the demo/example code and the documentation disagreed on how things should be implemented. It took some trial and error to find out which methods were correct. I wouldn't recommend this framework for development unless they have taken great strides in recent months.

I want to mention responsive web design because it has great potential. While it doesn't give you the web app feel and isn't really a web app framework, it is definitely a good way to go if you need to develop a mobile web site. The pages load faster than they would using a web app framework (there is much less styling and JavaScript in the background). On the flip side, there are no fancy transitions, but that can be a good thing. You are in control of all the styling and the size of all the UI elements. Plus when designed right, it works on screens of all sizes -- there is no need for special mobile sub-domains or redirects.

In the end, no web app framework is perfect and completely replicates the native experience -- that hasn't happened, yet. With this said, I recommend jQuery Mobile and responsive web design as my favorites. They are different solutions for different problems (jQuery Mobile for a native-app experience, responsive for informational sites), but I would strongly suggest evaluating them if you have a new mobile web project coming up.

Monday, October 3, 2011

jQuery Mobile Date Picker

I've been working with jQuery Mobile on a new form. I have the need for a datepicker and was really impressed with what a man by the name of jstage has put together. It is really thurough. So, if you are looking a flexible, mobile date picker, this is a good one.

Friday, January 8, 2010

jQuery and onKeyUp

jQuery has the method keyup to take the place of the html attribute onkeyup. So, for example, let's say want to run a javascript function each time escape is pushed. You would do this like so:
$(document).keyup(function(event) {
  if(event.keyCode == 27) { // Capture Esc key
      doSuperSpecialFunction();
  }
});

With this script anytime a key is pressed and goes up in the body of the document, the function specified runs. Simply replace the keyCode number (27, above) with the number that corresponds to your key (like 13 for enter or 8 for backspace). Remember, you must have jQuery "installed" in order for this to work.

Tuesday, November 24, 2009

Browser detection with jQuery

Those who create web apps to work for the widest possible audience, know that overcoming browser quirks is an unfortunate part of the job. The two greatest pains for me are IE6 and IE7, both common browsers with an uncommon ability to screw up my pages. (I think IE8 is a wonderful improvement to this line of browsers.) Recently I found out how to determine if a browser is IE7 or lower using this handy jQuery statement:

<script type="text/javascript">
if ($.browser.msie && (parseFloat($.browser.version) < 8)) {
// Do something for IE7 or IE6
// Like replace some image src with a gif (instead of transparent png)
// or change a style to look right
}
</script>

Of course, you must have the jQuery library included on the page before this. But this little script is great for dealing with those demanding IE-specific quirks, like display:inline uniqueness, select-box borders and transparent png support.

Wednesday, October 14, 2009

jQuery, checkbox status

I wanted to find the state of a checkbox and hide or show some text using jQuery. The thing that I got stuck on was determining if the checkbox was checked. This is how I ended up doing it:

<script type="text/javascript">
$(document).ready(function() {
$("input[name='cbname']").click( function() {
if ($(this).attr('checked'))
$('#text').hide();
else
$('#text').show();
});
});
</script>
<input type="checkbox" name="cbname"> Hide!
<div id="text">
Disappearing Text
</div>

Simply checking the attribute 'checked' of the checkbox returns its state (in jQuery 1.3.2, at least).

Thursday, July 2, 2009

jQuery's getJSON

I recently had a struggle getting jQuery's $.getJSON function to work on Internet Explorer (IE6 & IE7). I tried and tried to debug the javascript, but was getting no where. After giving up for a while and coming back to it the next day, I thought of checking the target file—the file jQuery was fetching asynchronously—for problems.

It turns out that IE doesn't like JSON encoded documents that are specified as UTF-8. Not sure what the problem is, but the document has to be returned in a format IE likes. If not, IE will not allow jQuery to process it. Now, I had a header on this file that specified the content-type and charset. But, I changed it and instead I put only the content-type at the top of my JSON-returning PHP files:

<?PHP
header("Content-Type: application/json");
?>

Why does IE balk at UTF-8 specified charsets for JSON-encoded responses?? Who knows. But, from the research I've done, specifying the charset in the HTTP header is not something that is required. I am sure there are good reasons to specify the charset, but this (above) works great for me.

Friday, April 10, 2009

javascript wonderland

There is a lot you can do with JavaScript and DHTML. You can have custom pop-up messages, you can make things move around the screen, you can have pop-down menus, you can even send data to web servers (AJAX). But, it takes some work to get everything running smoothly. Especially when you want a certain user interface to work great no matter what browser is used.

jQuery is a great solution for JavaScript and user interface problems. They have a wonderful library of visual affects and more. Just take a look at their demos to get a feel for what I am talking about (in terms of UI). Then, if you want to integrate it into your own site, just download the code and plug it in (with a few tweaks and bumps - but that is expected, right?). It is a great way to get good functionality going quickly and reliably in a web site.