Categories
Archive for category jQuery
This is a function I am using in my application so I could use keyboard keys to browse through a lit of tasks. My problem was that som of the tasks were hidden (in my example did not have the class “visible”) so I did not want to go through them when using the up and down keys while browsing the list of tasks. I only wanted to use click() on the next visible list item.
I had to use prevAll() & nextAll with a specific slection of a class ‘visible’ but and reaching for the first match.
This the particular piece of code in caffeescript (again, its just jquery without brackets)
prev_list = $(current_list).prevAll('li.visible:first')
My function is a bit longer as I am checking by other stuff but this is the simplified version of it.
focus_on_prev_task = ->
$('#data_ajax_cover li').each ->
current_list = $(this)
prev_list = $(current_list).prevAll('li.visible:first')
$(prev_list).click()
Catch the ajax:beforeSend and ajax:success on rails 3.1 remote forms with cafeescript
21/06/11 No CommentsYou might want to display your custom progress bar when using remote ajax forms in rails 3.1. This is how you would bind your custom functions to the events in cafeescript
rails_remote_forms = ->
$('form[data-remote]').bind "ajax:beforeSend", ->
ajax_display_progress_bar()
$('form[data-remote]').bind "ajax:success", ->
ajax_success_message()
When autosuggestions are turning off the focus I got rid of them like this.
The script is in caffeescript but pure jQuery is not much different
#Turn autocomplete off on all forms
# ============================================================================
turn_autocomplete_off = ->
$('form').each ->
$(this).attr('autocomplete', 'off')
$(this).find('input').attr('autocomplete', 'off')
Caffee Script has become the default in rails 3.1
The syntax is pretty interesting and for those of you who do not like the brackets it is going to be a gogo.
You only need to make sure that your indenting is correct
This is how you define a simple function
my_lovely_function = -> alert "hello"
This is how you define a simple function with a variable
my_lovely_function = (variable) -> alert "hello"
And this is how you call the function
my_lovely_function variable
As you can see most of the brackets are gone. You can still use jQuery in Caffee Script. jQuery is part of Rails 3.1 as well so we are all good
The new jQuery >1.5.0 does not support the syntax for the hover we have been using so far but there is a better way.
This was the old way.
$('#users_edit p.edit_in_place_paragraph').live('hover', function (ev) {
if (ev.type == 'mouseover') {
// your on hover stuff..
}
if (ev.type == 'mouseout') {
// your hover out stuff....
}
});
This is the new way, which works.
$('#users_edit p.edit_in_place_paragraph').live({
mouseenter:
function()
{
// your on hover stuff..
},
mouseleave:
function()
{
// your hover out stuff....
}
});
Just a mental note for the small issue I have find out when working with cookies.
During the testing of my latest app. I have realized that there IE7/8 will return null and Firefox will return empty string when you request the value of empty cookie. You might need to check for both cases when doing this kind of checking.
Why would you ever wanted to do this?
In my example I set certain preferences on the site into the cookie. Once the user loggs out the cookie is destroyed. I need to say that this is session cookie so it will also get destroyed when the user closes the browser.
My scripts checks the value of the cookie and the page behaves differently if the depending of the cookie. If the cookie’s value is null, empty string or undefined I want the page to behave using default scenario.
I have just recently implemented this slide show to one of my clients so I thought why not to share it with you guys.
The sideshow is again quite flexible. It should be able to slide any kind of elements you specify in $elements variable. It is up to you. It could be images, div with css background images, list items with text only and so on.
You can set the hide and show intervals use the variables $hideInterval, $showInterval. The navigation which allows you to click previous and next is inserted into the DOM after the page is loaded. You will need to specify the html element in the variable $insert_nav. If you look close the nav will be inserted before this element insertBefore($insert_nav) but you could just simply change this to insertAfter() if you need to.
You could also change the effects inside the function from “fadeIn()” to “show()” and so on.
// Slideshow of the board
$(function () {
$insert_nav = $('#board_one');
//Insert Nav into the DOM
$('<ul id="board_nav"><li id="previous" title="previous">previous</li><li id="next" title="next">next</li></ul>').insertBefore($insert_nav);
$elements = $('.board_element');
$elementsSize = $($elements).length;
// Setting the intervals for animation
$n=0;
$interval = 5000;
$hideInterval = 30;
$showInterval = 500;
$stop = false;
loopelements();
// Loop through elements
function loopelements (){
if ($stop == 'next'){
if($n == $elementsSize){
$n = 0;
}
$($elements).fadeOut($hideInterval);
$($elements[$n]).fadeIn($showInterval);
}else if ($stop == 'prev'){
if($n == -1) {
$n = $elementsSize -1;
}
$($elements).fadeOut($hideInterval);
$($elements[$n]).fadeIn($showInterval);
}else {
$($elements).fadeOut($hideInterval);
$($elements[$n] ).fadeIn($showInterval);
$n++;
if($n == $elementsSize) $n = 0;
setTimeout(loopelements,$interval);
}
}
// Next button
$('#next').live('click', function (){
$n++;
$stop = 'next';
$(this).stop(true,true);
loopelements();
});
// Prev button
$('#previous').live('click', function (){
$n--;
$stop = 'prev';
$(this).stop(true,true);
loopelements();
});
});
I have build simple function which helps me to make my code nice and clean as well as to have general solution for “on_change” AJAX submit. I have named the function q_submit_ajax_on_change with q in the front because I use it in my quantify project. The function uses another pre-build function called q_submit_ajax_on_change which I will describe next. You called this function from anywhere you have your form which should be submitted via AJAX. You need to pass the element (input or textarea) which will be controlled by this function. The function basically checks the value of the element and if the value has changed then the data are submitted via AJAX on blur, which means when the user leaves the element.
function q_submit_ajax_on_change ($element, $form){
$($element).live('focus', function(){
$characters = $(this).attr('value');
});
$($element).live('blur', function(){
$current_characters = $(this).attr('value');
if($characters == $current_characters){
// No change ....
}else{
// Submit the Form when the user looses focus
q_ajax_form_submit($form, $('#system_message'));
}
});
}
The data are submitted using the q_ajax_form_submit function which I have also build for quantify project. It requires 2 variables, form and the id of the element where the success or failure message should be displayed. This function uses the basic jQuery Ajax function but on top displays the progress bar (handled by q_display_progress_bar() function and displays custom success and failure messages, using functions – q_display_success_message() and q_display_failure_message().
function q_ajax_form_submit (form, message_box){
q_display_progress_bar();
$form = form
$url = $form.attr('action');
$dataString = $form.serialize();
$.ajax({
type: "POST",
url: $url,
data: $dataString,
success: function (data) {
q_display_success_message();
// Return the data as well
$(message_box).html(data);
},
error: function () {
q_display_failure_message();
}
});
}
This is my basic framework for the AJAX calls. Here are the last three functions mentioned before.
Function q_display_progress_bar basically inserts animated gift which is specified as background css image for ajax_loader id. You can see this loader is inserted before id called content. We could also specify variable instead of id directly as I have done in my case.
Function q_display_success_message is pretty specific for my case where I have decided to insert the “Saved” image into the page and fade it out. You can see that I remove the animated loader from the page before I insert the “saved” image.
The q_display_failure_message is doing basically the same what the success function but is using one more additional function which scrolls the page to the top. q_scroll_top(110,250) as well as inserts the black overlay using function q_insert_overlay(‘body’).
function q_display_progress_bar (){
// Display animation during the ajax call
$('<span id="ajax_loader"></span>').insertBefore('#content');
}
function q_display_success_message (){
// Display "Saved" message when ajax returns success
$('#ajax_loader').remove();
$('<span class="saved">Saved</span>').insertBefore('#content');
$('.saved').hide().fadeIn(500).delay(1000).fadeOut(500);
setTimeout(function(){
$('.saved').remove();
},2000);
}
function q_display_failure_message (){
// Display "Failure" message when ajax returns failure
$('#ajax_loader').remove();
// Insert Overlay background
q_insert_overlay('body');
$('<span class="failure">There has been problem. Some of data might not be saved.<span id="small_close">close</span><span id="big_close">Close</span></span>').insertBefore('#content');
$('.saved').hide().fadeIn(500);
// Scroll the view point
q_scroll_top(110,250);
}
So here are the last two functions. These are visual functions so you do not need to use them and they might not be the right solution in your case. I have specified semi transparent background css image for popup_cover which brings the black overlay on top of which the Ajax messages are positioned.
function q_insert_overlay($body){
// Inserts the overlay into the page
$window_height = $($body).height();
$('<div id="popup_cover"></di>').insertBefore($('#page'));
$('#popup_cover').css({
'height': $window_height
});
}
function q_scroll_top ($top, $time){
$('html, body').animate({
scrollTop: $top
}, $time);
}
And this is it. This brings modern web application into the life where pages do not have to be reloaded and consume users time so user can focus more on the core of her/his work.
Based on user statistics, users prefer to have the form validated as they type so they do not have to come back and correct stuff after they submitted the whole form. In our example I will show you how to validate the form with multiple email addresses. You can start by defining CSS class called “incorrect_email” where you define how the input field should look like when the validation fails. I can imagine you will define something like this.
.incorrect_email {
border: 1px solid red;
background: pink;
color: red;
}
After this we will create jQuery script which will validates every input field which has assigned class “email_validation”. This could be done in so many ways but I have chosen this for its simplicity. The key here is to user blur() function to validate the input field right after the user leaves the field and it does not matter if its by pressing TAB or clicking with mouse.
$('form input').blur(
// check the input fields which has a class email_validation as we expect more email fields in the form
if($(this).hasClass('email_validation')){
// get the current value
var email = $(this).val();
// define regular expression for email
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// validate the email address
if(!filter.test(email)){
// email incorrect add the class "incorrect_email"
$(this).addClass("incorrect_email")
// email corrected remove the class "incorrect_email"
}else if(filter.test(email)){
// you could also check in this point if the the input has already the class...
$(this).removeClass("incorrect_email");
}
}
);
This can be quite handy if you have forms with multiple fields and few of them are email type (for example: inviting your contacts). You might also need to do some other type of validations like if the fields are empty and so on, this is just a part of your validation function.