jQuery plugin for Facebook "Like" Button - jquery-ui

On lots of sites now, you can see a Facebook "Like" Button.
- When depressed, it changes background color.
- When mouse-overed, it allows you to write some additional text
I love this interface - lightweight action, but allow for expression of more data if the user wants to.
Anyone has written a similar plugin?
UPDATE:
See: http://www.engadget.com/2010/05/30/htc-evo-4g-gets-hacked-froyo-port-sense-ui-be-damned/ at the bottom of a post, you will see the facebook like button

I don't know of such a plugin for jQuery, but writing the user-interface is quite simple.
(Edit: Actually I just thought of a place where I could use this feature myself. I might just as well write a proper plugin based on this next week if I have the time, and edit it here. For the time being, below is what I originally posted...)
All you need is a couple of divs:
<div id="thebutton">Click me!</div>
<div id="thebox" style="display:none;">Content goes here</div>
And some jQuery:
<script type="text/javascript">
$(function () {
$('#thebutton')
.click(function () {
//Show/hide the box
$(this).toggleClass('activated');
$(this).hasClass('activated') ? $('#thebox').fadeIn() : $('#thebox').fadeOut();
})
.mouseenter(function () {
//If the button is .activated, cancel any delayed hide and display the box
$(this).addClass('hovering');
if ($(this).hasClass('activated')) {
$('#thebox').clearQueue().fadeIn();
}
})
.mouseleave(function () {
//Hide the box after 300 milliseconds (unless someone cancels the action)
$(this).removeClass('hovering');
$('#thebox').delay(300).fadeOut();
});
$('#thebox')
//When hovering onto the box, cancel any delayed hide operations
.mouseenter(function () { $(this).clearQueue(); })
//When hovering off from the box, wait for 300 milliseconds and hide the box (unless cancelled)
.mouseleave(function () { $(this).delay(300).fadeOut(); });
});
</script>
The rest is pretty much just CSS for #thebutton, #thebox, .hovering and .activated.
Here's a spartan look I used while writing this:
<style type="text/css">
#thebutton { width: 100px; background-color: #eee; text-align: center; padding: 10px; cursor: pointer; }
#thebutton.activated { font-weight: bold; }
#thebutton.hovering { color: Blue; }
#thebox { background-color: #eee; position:relative; width: 300px; height: 200px; padding: 10px; top: 5px; display: none;}
</style>

How about this jquery plugin: http://socialmediaautomat.com/jquery-fbjlike-js.php
It's really simple to set up and lets you perform some neat tasks in combination with the jquery cookie plugin (have a look at the demo page).

You can handle the hover, mousedown, and mouseup events and change the button's content or style.

Is not a plugin it uses the Facebook Javascript SDK. You load it by placing this at bottom of your document:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
Add this attribute to your HTML tag(the actual HTML tag right after the DOCTYPE):
xmlns:fb="http://www.facebook.com/2008/fbml"
And then you can place this snippet wherever you want a Like button:
<fb:like></fb:like>

Using the $('#your-button').button(); function from the jQuery UI library gives this functionality, and a whole lot more.
http://jqueryui.com/themeroller/

Related

Why the DIV is draggable once in IE using Crossrider & JQueryUI ? & no dragstop event fired?

I'm using Crossrider, I want to add a draggable div to the page's DOM.
The following code works well on Chrome and Firefox, and the dragstop handler function is fired for both Chrome and Firefox without any problems.
But for IE, the div is draggable once ! i.e. Once the div is dropped, it cannot be dragged again, and more strange is that the dragstop event handler is not fired at all in IE !?
How to fix this in IE !?
Here is the code:
extension.js file
appAPI.ready(function(jQuery) {
appAPI.resources.jQueryUI('1.10.1');
appAPI.resources.includeCSS('styles.css');
var $div = jQuery('<div class="square" ></div>').appendTo('body');
$div.draggable( {containment: "window", scroll: false} );
$div.bind('dragstop', function() {
console.log("drag stopped ...");
});
});
styles.css file
.square {
display:block;
z-index: 1000001;
background-color: #000000;
height: 100px;
width: 100px;
top: 0px;
left: 0px;
position: fixed;
}
Kindly note, that I tried the code without crossrider and I run it on IE, it works well. You can try it by using this link: http://jsfiddle.net/GHaMV/
I ran into the same problem using Crossrider and managed to fix the issue by declaring a handler function that returns the draggable element, so your code should look as follows:
$div.draggable({
containment: window,
helper: function() {
return $div;
}
});
Hope it helps...
There is no dragstop event, just the stop hook (see the docs):
Use it like this:
$div.draggable({
containment: "window",
scroll: false,
stop: function() {
console.log("drag stopped ...");
}
});

jQuery Mobile - Slide In Alert Bar CSS over Header

I am trying to make an alert bar slide in over my header bar in jQuery mobile. So far I have got the slide in down, but I am having trouble with the CSS. I originally tried make the outer most div with position: absolute; top 0px: which makes it slide over the header from the top, but then inside Safari on the iPhone, the close button is cut off and you have to scroll to the right. How do I fix that?
Here is the HTML code for the alert bar:
<div class="ui-bar ui-bar-b error" style="position: absolute; top: 0px;">
<h3>
Form Validation Errors
</h3>
<div style="display:inline-block; width:8%; margin-top:0px; float: right;">
Dismiss
</div>
<ul class="validation_errors_list"></ul>
</div>
I ended up finally use this CSS. The alert bar slides directly over the header.
//you only really need this just to get it to slide over the header nicely and make sure you use top:0 if you always want it to be at the top. The plugin I made shows in/out the error message at position you are scrolled to in the document
.alert{
position: absolute;
z-index: 9998;
width: 100%;
height: 30px;
display: none;
color: #ffffff;
text-shadow: none;
font-family: Helvetica,Arial,sans-serif;
}
//This CSS is only used if you have an X button to close the alert. See the plugin below.
.alert-button-container{
display:inline-block;
margin-top:-10px;
margin-right: 15px;
float: right;
}
Here is my HTML Code (note the ui-bar class is a jQuery mobile class that you need to add so you don't have to mess around some of the width and sizing stuff).
<div class="ui-bar alert">
<div class="alert-message"></div>
</div>
Here is a custom plugin I made from jQuery to do this alert bar.
Features + Use Cases
Features: Fades In/Out gracefully, can inject custom HTML error messages, can render a list of messages, slides over header, has a close X button for error messages, works on all browsers that I have tested so far (IE, iOS, Firefox), error messages appear at the position you are scrolled to in the document. No more have to scroll up to see the error :)
Form Validation Errors. You can pass in an array of error messages and it will parse it into a list.
var messages = new Array();
messages[0] = 'My Message';
//prevent from showing accidentally
if(messages.length > 0)
{
$(".alert").alertBar('error', "<h2>Form Validation Errors</h2>", {
'errorMessages': messages
});
}
Success or action messages:
$(".alert").alertBar('success', 'Removed From Your Itinerary');
////////////plugin code
(
function($) {
$.fn.alertBar = function(alertType, alertMessage, userOptions) { //Add the function
var options = $.extend({}, $.fn.alertBar.defaultOptions, userOptions);
var $this = $(this);
$this.addClass(options.cssClass)
.empty()
.html(alertMessage)
.css('top', $(document).scrollTop());
if(alertType == 'success')
{
$this
.fadeIn()
.addClass('alert-success')
.delay(options.animationDelay)
.fadeOut();
}
if(alertType == 'error')
{
var button = $('<div>')
.addClass('alert-button-container')
.append(
$('<a>').attr({
'href': '#',
'data-role': 'button',
'data-icon': 'delete',
'data-iconpos': 'notext',
'class': 'dismiss-error'
})
.append('Dismiss')
);
//build error container
$this
.addClass('alert-error')
.append(button);
//add optional items to error container
if(options.errorMessages)
{
var $messageList = $('<ul>').addClass('error-message-list');
for ( var i=0, len=options.errorMessages.length; i<len; ++i ){
$messageList.append(
$('<li>')
.append(options.errorMessages[i])
);
}
$this.append($messageList);
}
//show alert bar
$this
.trigger('create')
.fadeIn();
$(".dismiss-error").live('click', function(){
$this.fadeOut();
});
}
if(alertType == 'informational')
{
$this
.addClass('alert-informational')
.fadeIn()
.delay(options.animationDelay)
.fadeOut();
}
return $this;
};
$.fn.alertBar.defaultOptions = {
cssClass : 'alert',
alertBarType: '',
animationDelay: 1500
};
})(jQuery);
additional CSS classes if you use this. It just changes the color of the bar.
.alert-success{
background-color: #8cc63f;
}
.alert-error{
background-color: #ed1c24;
height: auto;
}
.alert-informational{
background-color: #0071bc;
}
Example picture:

jquery ui draggable deaccelerate on stop

i am using jquery ui draggable do drag a div around. whats the best way to smoothly ease out the drag after the drag stopped?
assuming the drag stopped abruptly.
thank you
Implementing draggables with easing might work for you. This is a simplified solution from my answer to a previous thread, which was more specific:
JQuery draggable with ease
HTML:
<div id="draggable">
</div>
CSS:
#draggable {
position: relative;
width: 100px;
height: 100px;
background-color: whitesmoke;
border: 2px solid silver;
}
Javascript:
$(function() {
$("#draggable").draggable({
helper: function(){
// Create an invisible div as the helper. It will move and
// follow the cursor as usual.
return $('<div></div>').css('opacity',0);
},
drag: function(event, ui){
// During dragging, animate the original object to
// follow the invisible helper with custom easing.
var p = ui.helper.position();
$(this).stop().animate({
top: p.top,
left: p.left
},1000,'easeOutCirc');
}
});
});
jsFiddle demo: http://jsfiddle.net/NJwER/26/

$.Ajax send with progress bar using jquery

Hi folks
I use $.ajax functionality to send data to server and with this method I removed most of postback pages it works but I need some progress bar to show visitors there are some progress now it shows nothing after some second it shows result but i think a message or small picture is need in my web site. How I can implement it with simple jquery code ? something popup and shows the page is in the progress.
And also I need to add some other jquery to prevent other click during the progress is it possible ?
You can do something like
$("elemnt").click(function(){
$("loader-img").show();
$.ajax({
url : "your url",
complete: function(){
$("loader-img").hide();
}
});
});
The loader image can be an page blocking div, to block the user from doing anything with a image at the center of the viewport.
Here the complete event is used since this event is called in case of a successful/failed ajax request.
EDITED
You can do something like
<style type="text/css">
.blocker{
z-index: 99999;
opacity: .5;
height: 100px;
position: fixed;
background: none repeat scroll 0 0 lightgrey;
width: 100%;
}
.blocker .img{
position: fixed;
color: red;
}
</style>
<body>
<div class="blocker" style="display: none">
<div class="img">img</div>
</div>
.............
.............
.............
Then In Script
function showBlocker(){
$(".blocker .img").css({
top: $(window).height() / 2,
left: $(window).width() / 2
});
$(".blocker").show().css({
height: $(document).height()
});
}
Then call the showBlocker() method to show the blocker.
You can tweak the answer to fit into your need. This is just a sample how it can be achieved
You can show a loading image before the AJAX call starts and then hide it in the callback function.
Something like
// handler for ajax trigger
$("#yourelement").click(function(){
// your loading image object
$("#yourimage").show();
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$("#yourimage").hide();
}
});
});

Notify panel similar to stackoverflow's

Remember the little div that shows up at the top of the page to notify us of things (like new badges)?
I would like to implement something like that as well and am looking for some best practices or patterns.
My site is an ASP.NET MVC app as well. Ideally the answers would include specifics like "put this in the master page" and "do this in the controllers".
Just to save you from having to look yourself, this is the code I see from the welcome message you get when not logged in at stackoverflow.
<div class="notify" style="">
<span>
First time at Stack Overflow? Check out the
FAQ!
</span>
<a class="close-notify" onclick="notify.close(true)" title="dismiss this notification">×</a>
</div>
<script type="text/javascript">
$().ready(function() {
notify.show();
});
</script>
I'd like to add that I understand this perfectly and also understand the jquery involvement. I'm just interested in who puts the code into the markup and when ("who" as in which entities within an ASP.NET MVC app).
Thanks!
This answer has a complete solution.
Copy-pasting:
This is the markup, initially hidden so we can fade it in:
<div id='message' style="display: none;">
<span>Hey, This is my Message.</span>
X
</div>
Here are the styles applied:
#message {
font-family:Arial,Helvetica,sans-serif;
position:fixed;
top:0px;
left:0px;
width:100%;
z-index:105;
text-align:center;
font-weight:bold;
font-size:100%;
color:white;
padding:10px 0px 10px 0px;
background-color:#8E1609;
}
#message span {
text-align: center;
width: 95%;
float:left;
}
.close-notify {
white-space: nowrap;
float:right;
margin-right:10px;
color:#fff;
text-decoration:none;
border:2px #fff solid;
padding-left:3px;
padding-right:3px
}
.close-notify a {
color: #fff;
}
And this is javascript (using jQuery):
$(document).ready(function() {
$("#message").fadeIn("slow");
$("#message a.close-notify").click(function() {
$("#message").fadeOut("slow");
return false;
});
});
And voila. Depending on your page setup you might also want to edit the body margin-top on display.
Here is a demo of it in action.
After snooping around the code a bit, here's a guess:
The following notification container is always in the view markup:
<div id="notify-container"> </div>
That notification container is hidden by default, and is populated by javascript given certain circumstances. It can contain any number of messages.
If the user is not logged in
Persistence: Cookies are used to keep track of whether a message is shown or not.
Server side generated code in the view:
I think stackoverflow only shows one message if you aren't logged in. The following code is injected into the view:
<script type="text/javascript">
$(function() { notify.showFirstTime(); });
</script>
The showFirstTime() javascript method just determines whether to show the "Is this your first time here?" message based on whether a cookie has been set or not. If there is no cookie, the message is shown. If the user takes action, the cookie is set, and the message won't be show in the future. The nofity.showFirstTime() function handles checking for the cookie.
If the user is logged in
Persistence: The database is used to keep track of whether a message has been shown or not.
Server side generated code in the view:
When a page is requested, the server side code checks the database to see what messages need to be displayed. The server side code then injects messages in json format into the view and puts a javascript call to showMessages().
For example, if I am logged into a view, I see the following in the markup at SO:
<script type="text/javascript">
1
2 var msgArray = [{"id":49611,"messageTypeId":8,"text":"Welcome to Super User! Visit your \u003ca href=\"/users/00000?tab=accounts\"\u003eaccounts tab\u003c/a\u003e to associate with our other websites!","userId":00000,"showProfile":false}];
3 $(function() { notify.showMessages(msgArray); });
4
</script>
So the server side code either injects code to call the "showFirstTime" method if the user is not logged in or it injects messages and calls "showMessages" for a logged in user.
More about the client side code
The other key component is the "notify" JavaScript module Picflight has de-minified (you can do the same using yslow for firebug). The notify module handles the populating of the notification div based on the server side generated javascript.
Not logged in, client side
If the user is not logged in, then the module handles events when the user X's out the notification or goes to the FAQ by creating a cookie. It also determines whether to display the first time message by checking for a cookie.
Logged in, client side
If the user is logged in, the notify module adds all the messages generated by the server into the notification div. It also most likely uses ajax to update the database when a user dismisses a message.
Though these are by no means official, the common practices that I follow would result in something like this:
Create the element that will act as the notification container in the markup, but hide it by default (this can be done numerous ways - JavaScript, external CSS, or inline styles).
Keep the scripts responsible for the behavior of the notification outside of the markup. In the example above, you can see there is an onclick as well as another function that fires on page load contained in the markup. Though it works, I see this as mixing presentation and behavior.
Keep the notification message's presentation contained in an external stylesheet.
Again, these are just my common practices stated in the context of your question. The thing with web development, as the nature of your question already shows, is that there are so many ways to do the same thing with the same results.
I see the following jQuery function? I beleive that injects the html into the div with id notify-container.
I don't understand how this JS is used and called based on certain events, perhaps someone can explain.
var notify = function() {
var d = false;
var e = 0;
var c = -1;
var f = "m";
var a = function(h) {
if (!d) {
$("#notify-container").append('<table id="notify-table"></table>');
d = true
}
var g = "<tr" + (h.messageTypeId ? ' id="notify-' + h.messageTypeId + '"' : "");
g += ' class="notify" style="display:none"><td class="notify">' + h.text;
if (h.showProfile) {
var i = escape("/users/" + h.userId);
g += ' See your profile.'
}
g += '</td><td class="notify-close"><a title="dismiss this notification" onclick="notify.close(';
g += (h.messageTypeId ? h.messageTypeId : "") + ')">×</a></td></tr>';
$("#notify-table").append(g)
};
var b = function() {
$.cookie("m", "-1", {
expires: 90,
path: "/"
})
};
return {
showFirstTime: function() {
if ($.cookie("new")) {
$.cookie("new", "0", {
expires: -1,
path: "/"
});
b()
}
if ($.cookie("m")) {
return
}
$("body").css("margin-top", "2.5em");
a({
messageTypeId: c,
text: 'First time here? Check out the <a onclick="notify.closeFirstTime()">FAQ</a>!'
});
$(".notify").fadeIn("slow")
},
showMessages: function(g) {
for (var h = 0; h < g.length; h++) {
a(g[h])
}
$(".notify").fadeIn("slow");
e = g.length
},
show: function(g) {
$("body").css("margin-top", "2.5em");
a({
text: g
});
$(".notify").fadeIn("slow")
},
close: function(g) {
var i;
var h = 0;
if (g && g != c) {
$.post("/messages/mark-as-read", {
messagetypeid: g
});
i = $("#notify-" + g);
if (e > 1) {
h = parseInt($("body").css("margin-top").match(/\d+/));
h = h - (h / e)
}
} else {
if (g && g == c) {
b()
}
i = $(".notify")
}
i.children("td").css("border-bottom", "none").end().fadeOut("fast", function() {
$("body").css("margin-top", h + "px");
i.remove()
})
},
closeFirstTime: function() {
b();
document.location = "/faq"
}
}
} ();
StackOverflow uses jQuery - the JS code you posted from SO is a jQuery call. It'll do exactly what you want with almost no code. Highly recommended.
I wrote this piece of Javascript that does just that including stacking, staying with you as you scroll like Stack Overflow's does and pushing the whole page down whenever a new bar is added. The bars also expire. The bars also slide into existence.
// Show a message bar at the top of the screen to tell the user that something is going on.
// hideAfterMS - Optional argument. When supplied it hides the bar after a set number of milliseconds.
function AdvancedMessageBar(hideAfterMS) {
// Add an element to the top of the page to hold all of these bars.
if ($('#barNotificationContainer').length == 0)
{
var barContainer = $('<div id="barNotificationContainer" style="width: 100%; margin: 0px; padding: 0px;"></div>');
barContainer.prependTo('body');
var barContainerFixed = $('<div id="barNotificationContainerFixed" style="width: 100%; position: fixed; top: 0; left: 0;"></div>');
barContainerFixed.prependTo('body');
}
this.barTopOfPage = $('<div style="margin: 0px; background: orange; width: 100%; text-align: center; display: none; font-size: 15px; font-weight: bold; border-bottom-style: solid; border-bottom-color: darkorange;"><table style="width: 100%; padding: 5px;" cellpadding="0" cellspacing="0"><tr><td style="width: 20%; font-size: 10px; font-weight: normal;" class="leftMessage" ></td><td style="width: 60%; text-align: center;" class="messageCell"></td><td class="rightMessage" style="width: 20%; font-size: 10px; font-weight: normal;"></td></tr></table></div>');
this.barTopOfScreen = this.barTopOfPage.clone();
this.barTopOfPage.css("background", "transparent");
this.barTopOfPage.css("border-bottom-color", "transparent");
this.barTopOfPage.css("color", "transparent");
this.barTopOfPage.prependTo('#barNotificationContainer');
this.barTopOfScreen.appendTo('#barNotificationContainerFixed');
this.setBarColor = function (backgroundColor, borderColor) {
this.barTopOfScreen.css("background", backgroundColor);
this.barTopOfScreen.css("border-bottom-color", borderColor);
};
// Sets the message in the center of the screen.
// leftMesage - optional
// rightMessage - optional
this.setMessage = function (message, leftMessage, rightMessage) {
this.barTopOfPage.find('.messageCell').html(message);
this.barTopOfPage.find('.leftMessage').html(leftMessage);
this.barTopOfPage.find('.rightMessage').html(rightMessage);
this.barTopOfScreen.find('.messageCell').html(message);
this.barTopOfScreen.find('.leftMessage').html(leftMessage);
this.barTopOfScreen.find('.rightMessage').html(rightMessage);
};
this.show = function() {
this.barTopOfPage.slideDown(1000);
this.barTopOfScreen.slideDown(1000);
};
this.hide = function () {
this.barTopOfPage.slideUp(1000);
this.barTopOfScreen.slideUp(1000);
};
var self = this;
if (hideAfterMS != undefined) {
setTimeout(function () { self.hide(); }, hideAfterMS);
}
}
To use it you must use jQuery and ensure there are no margins or padding on the body of your page.
The parameter that the AdvancedMessageBar takes is optional. If provided it will cause the bar to disappear after a certain amount of time in milliseconds.
var mBar = new AdvancedMessageBar(10000);
mBar.setMessage('This is my message', 'Left Message', 'Right Message');
mBar.show();
If you want to stack these then just create more AdvancedMessageBar objects and they'll automatically stack.

Resources