Tag Archives: HTML

HTML

How to Customise ShareThis Settings – ShareThis

Hey everyone,

I’ve just added ShareThis to a website I’m currently working on. It’s basically a generator for all your typical social network plugins (Facebook Like, Twitter Share, Google+ etc). The main advantage I’ve found with using it is the detailed analytics.

While I haven’t had any major issues, there were a few customisations I had to make:

Change Title in ShareThis
Changing the title is pretty easy, simply use the st_title attribute:



Change/Set the URL that is Shared
I needed to set this when generating content via ajax to ensure that the correct URL was shared. Again, it’s pretty straight forward – just use the st_url attribute.



Re-initialising ShareThis buttons when using ajax
A follow on from the last issue is that ShareThis buttons will need to be reinitialised if additional content is generated via ajax:

//Re-initialise ShareThis
if (stButtons){
     stButtons.locateElements();
}

There’s a bit more info here, via this StackOverflow post:

Stop a Link from Going Anywhere – CSS/JavaScript

Hey everyone,

Another quick one – how to stop a link from doing anything. I’ve just come across a need to use a link that acts as a button. A slight UI issue with this is that clicking a hyperlink will with an href value of ‘#’ will push scroll to the top of the page.

There are a couple of ways to go about fixing this. Note the href value in the following:

<a href='javascript:void(0)' class='btn_show_reply' data-comment_id="">Reply

The second option is probably already familiar to anyone using ajax forms, simply have your function return false:

<a href='javascript:void(0)' onClick='myFunction()' id='my_awesome_link' data-comment_id="">Reply


function myFunction(){

   //Do some awesome stuff
   // ...

   //Return false to prevent link from affecting anything
   return false;
}

The third option is simply a jQuery-ish rehash of number 2:



/* Does some awesome stuff while preventing the calling link from directing the user */
$('#my_awesome_link').click(function(e) {

   //Do some awesome stuff and then prevent the link from directing user
   e.preventDefault();
});

Dropdown Button – Twitter Bootstrap

Hey everyone,

Just a quick post on how to create a dropdown button using Twitter Bootstrap. It’s pretty straight forward, once you’ve included all your CSS etc just add the following code:


Once you save that you should see something similar to the image below:

Twitter Bootstrap Dropdown Button

A standard twitter bootstrap dropdown button.

Change list item text alignment

To change the text alignment of this list items, all you need to do is adjust the text-align style assigned to the wrapper div.

Change dropdown button color

Once again, this is fairly simple, all you need to do is switch the button type. For instance, if you were after an orange button, you can swap btn-success with btn-warning. A list of the default styles is available on the Twitter Bootstrap site.

Let me know if you have any issues.

FullCalendar Example with Client-Side Event Updates

Hey everyone,

I’ve been mucking around with FullCalendar recently and decided to share one of the prototypes I’ve ended up with. It basically lets the user change the events without having to do a postback. A user simply has to click the event, type in the changes and hit update.

I’ve posted the code below, however there’s also a zip which is a little easier to manage. Note that you’ll probably want to clean it up a little if you plan to use it in production. The following libraries and plugins are also used:
jQuery
jQuery UI
jQuery FullCalendar
jQuery miniColors

What it Looks Like:

Full Calendar Example with Client Side Edits

Full Calendar Example with Client Side Edits

How to Use It:

It’s all pretty straight forward, but just in case any one runs into issues there are two parts to this example. First, you generate an event template. You can then drag and drop this template onto the calendar as many times as you want.

The second part allows you to edit existing events without posting back to the server. To do this, simply click an event and then make the necessary adjustments using the top panel on the right. Once you’re done, just press update event.

The example uses the standard title property, but also includes a few others: descriptions, price, available. You can change/remove these to suit your needs, just remember to pull them out of the JavaScript as well.

Zip:

Full Calendar Zip

Basic Example Page:


	

		
		
		
		
		
	
	

		
		
Background:

Border:

Text:





Description


One Hour
http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js http://js/jquery-ui-1.9.2.custom.min.js http://js/fullcalendar.js http://js/view_calendar.js http://js/jquery.miniColors.js

Basic JavaScript:

/* Wait for DOM to load etc */
$(document).ready(function(){

	//Initialisations
	initialise_calendar();
	initialise_color_pickers();
	initialise_buttons();
	initialise_event_generation();
	initialise_update_event();
});


/* Initialise buttons */
function initialise_buttons(){

	$('.btn').button();
}


/* Binds and initialises event generation functionality */
function initialise_event_generation(){

	//Bind event
	$('#btn_gen_event').bind('click', function(){

		//Retrieve template event
		var template_event = $('#external_event_template').clone();
		var background_color = $('#txt_background_color').val();
		var border_color = $('#txt_border_color').val();
		var text_color = $('#txt_text_color').val();
		var title = $('#txt_title').val();
		var description = $('#txt_description').val();
		var price = $('#txt_price').val(); 
		var available = $('#txt_available').val();

		//Edit id
		$(template_event).attr('id', get_uni_id());

		//Add template data attributes
		$(template_event).attr('data-background', background_color);
		$(template_event).attr('data-border', border_color);
		$(template_event).attr('data-text', text_color);
		$(template_event).attr('data-title', title);
		$(template_event).attr('data-description', description);
		$(template_event).attr('data-price', price);
		$(template_event).attr('data-available', available);

		//Style external event
		$(template_event).css('background-color', background_color);
		$(template_event).css('border-color', border_color);
		$(template_event).css('color', text_color);

		//Set text of external event
		$(template_event).text(title);

		//Append to external events container
		$('#external_events').append(template_event);

		//Initialise external event
		initialise_external_event('#' + $(template_event).attr('id'));

		//Show
		$(template_event).fadeIn(2000);
	});
}


/* Initialise external events */
function initialise_external_event(selector){

	//Initialise booking types
	$(selector).each(function(){

		//Make draggable
		$(this).draggable({
			revert: true,
			revertDuration: 0,
			zIndex: 999,
			cursorAt: {
				left: 10,
				top: 1
			}
		});

		//Create event object
		var event_object = {
			title: $.trim($(this).text())
		};

		//Store event in dom to be accessed later
		$(this).data('eventObject', event_object);
	});
}


/* Initialise color pickers */
function initialise_color_pickers(){

	//Initialise color pickers
	$('.color_picker').miniColors({
		'trigger': 'show',
		'opacity': 'none'
	});
}


/* Initialises calendar */
function initialise_calendar(){

	//Initialise calendar
	$('#calendar').fullCalendar({
		theme: true,
		firstDay: 1,
		header: {
			left: 'today prev,next',
			center: 'title',
			right: 'month,agendaWeek,agendaDay'
		},
		defaultView: 'agendaWeek',
		minTime: '6:00am',
		maxTime: '6:00pm',
		allDaySlot: false,
		columnFormat: {
			month: 'ddd',
			week: 'ddd dd/MM',
			day: 'dddd M/d'
		},
		eventSources: [
			{
				url: 'calendar_events.json',
				editable: false
			}
		],
		droppable: true,
		drop: function(date, all_day){
			external_event_dropped(date, all_day, this);
		},
		eventClick: function(cal_event, js_event, view){
			calendar_event_clicked(cal_event, js_event, view);
		},
		editable: true
	});	

	//Initialise external events
	initialise_external_event('.external-event');
}


/* Handle an external event that has been dropped on the calendar */
function external_event_dropped(date, all_day, external_event){

	//Create vars
	var event_object;
	var copied_event_object;
	var duration = 60;
	var cost;

	//Retrive dropped elemetns stored event object
	event_object = $(external_event).data('eventObject');

	//Copy so that multiple events don't reference same object
	copied_event_object = $.extend({}, event_object);
	
	//Assign reported start and end dates
	copied_event_object.start = date;
	copied_event_object.end = new Date(date.getTime() + duration * 60000);
	copied_event_object.allDay = all_day;

	//Assign colors etc
	copied_event_object.backgroundColor = $(external_event).data('background');
	copied_event_object.textColor = $(external_event).data('text');
	copied_event_object.borderColor = $(external_event).data('border');

	//Assign text, price, etc
	copied_event_object.id = get_uni_id();
	copied_event_object.title = $(external_event).data('title');
	copied_event_object.description = $(external_event).data('description');
	copied_event_object.price = $(external_event).data('price');
	copied_event_object.available = $(external_event).data('available');

	//Render event on calendar
	$('#calendar').fullCalendar('renderEvent', copied_event_object, true);
}


/* Initialise event clicks */
function calendar_event_clicked(cal_event, js_event, view){

	//Set generation values
	set_event_generation_values(cal_event.id, cal_event.backgroundColor, cal_event.borderColor, cal_event.textColor, cal_event.title, cal_event.description, cal_event.price, cal_event.available);
}


/* Set event generation values */
function set_event_generation_values(event_id, bg_color, border_color, text_color, title, description, price, available){

	//Set values
	$('#txt_background_color').miniColors('value', bg_color);
	$('#txt_border_color').miniColors('value', border_color);
	$('#txt_text_color').miniColors('value', text_color);
	$('#txt_title').val(title);
	$('#txt_description').val(description);
	$('#txt_price').val(price);
	$('#txt_available').val(available);
	$('#txt_current_event').val(event_id);
}


/* Generate unique id */
function get_uni_id(){

	//Generate unique id
	return new Date().getTime() + Math.floor(Math.random()) * 500;
}


/* Initialise update event button */
function initialise_update_event(){
	var test = $('#calendar').fullCalendar( 'clientEvents');
	//Bind event
	$('#btn_update_event').bind('click', function(){

		//Create vars
		var current_event_id = $('#txt_current_event').val();

		//Check if value found
		if(current_event_id){

			//Retrieve current event
			var current_event = $('#calendar').fullCalendar('clientEvents', current_event_id);

			//Check if found
			if(current_event && current_event.length == 1){

				//Retrieve current event from array
				current_event = current_event[0];

				//Set values
				current_event.backgroundColor = $('#txt_background_color').val();
				current_event.textColor = $('#txt_text_color').val();
				current_event.borderColor = $('#txt_border_color').val();
				current_event.title = $('#txt_title').val();
				current_event.description = $('#txt_description').val();
				current_event.price = $('#txt_price').val();
				current_event.available = $('#txt_available').val();

				//Update event
				$('#calendar').fullCalendar('updateEvent', current_event);
			}
		}
	});
}

Stylesheet

body{
	font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
	font-size: 12px;
}

#content_wrapper{
	width: 820px;
	margin-left: auto;
	margin-right: auto;
}

#calendar{
	width: 650px;
	float: left;
}

.btn{
	font-size: 85%
	margin-top: 10px;
}

#event_generation_wrapper{
	float: left;
	width: 120px;
	background-color: #DDD;
	margin-left: 20px;
	margin-top: 40px;
	border: 1px solid #4297D7;
	background-color: #FCFDFD;	
	-moz-border-radius: 3px;
	-webkit-border-radius: 3px;
	border-radius: 3px;
	padding: 10px 5px 10px 5px;
}

#event_generation_wrapper .left{
	float: left;
	width: 70px;
}

#event_generation_wrapper .right{
	float: left;
	max-width: 25px;
	margin-left: 10px;
}

#event_generation_wrapper input{
	width: 112px;
}

#event_generation_wrapper textarea{
	width: 110px;	
	height: 50px;
}

#event_generation_wrapper .miniColors-triggerWrap{	
	margin-bottom: 5px;
}

#event_generation_wrapper .text{
	padding-top: 1px;	
	margin-bottom: 5px;
	line-height: 10px;
}


#external_events{
	float: left;
	width: 130px;
	background-color: #DDD;
	margin-left: 20px;
	margin-top: 40px;
	border: 1px solid #4297D7;
	background-color: #FCFDFD;	
	-moz-border-radius: 3px;
	-webkit-border-radius: 3px;
	border-radius: 3px;
}

#external_events .external-event{
	width: 100px;
	margin: 5px;
	font-family: Verdana, Arial, sans-serif;
	border: 1px solid #36C;
	padding: 3px;
	text-align: center;
	background-color: #36C;
	color: white;
	cursor: pointer;
	-moz-border-radius: 3px;
	-webkit-border-radius: 3px;
	border-radius: 3px;
}

#calendar .ui-widget-header{
	font-weight: normal;
	padding: 3px 3px 3px 3px;
}

#calendar .fc-header-title{
	font-weight: normal;
}

#external_event_template{
	display: none;
}

Basic List of Events (JSON):

[
    "0",
    {
        "allDay": "",
        "title": "Test event",
        "id": "821",
        "start": "2012-11-23 14:00:00",
        "end": "2012-11-23 15:00:00"        
    },
    "1",
    {
        "allDay": "",
        "title": "Test event 2",
        "id": "822",        
        "start": "2012-11-23 9:00:00",
        "end": "2012-11-23 10:00:00"
    },
    "2",
    {
        "allDay": "",
        "title": "Test event 3",
        "id": "823",        
        "start": "2012-11-24 8:00:00",
        "end": "2012-11-24 6:00:00"
    },
    "3",
    {
        "allDay": "",
        "title": "Test event 4",
        "id": "824",        
        "start": "2012-11-27 6:00:00",
        "end": "2012-11-27 7:00:00"
    }
]

Let me know if you have any issues or something to add!

Cheers,
Chris

How to Reset ID of an Element – jQuery

Hey All,

Just a quick post on how to set the ID of an element (in this case a div) with jQuery. I needed to use this to dynamically clone elements.


WOOOOOOOOOOOOW
$('#my_test_id').attr('id', 'my_new_id');

The script above sets the id of div to my_new_id. If you’re interested, there’s a whole heap of documentation on the jquery site:
– Attr: http://api.jquery.com/attr/
– Clone: http://api.jquery.com/clone/

Modal Popup – Twitter Bootstrap

Just a quick post on how to create a modal popup using twitter bootstrap:

Step #1:

Add the following to a page element such as a link or button in order to open the modal:

     href="modal_content_name"
     data-toggle="modal"

i.e.

Add Image

Step #2:
Create a content div i.e.


And that’s all there is to it, just make sure you’ve included the bootstrap-modal.js file.

Modal Popup - Twitter Bootstrap

Modal Popup - Twitter Bootstrap


Open Twitter Bootstrap Modal Popup on Page Load:
In order to open the modal dialog on page load simply add the following JavaScript:


    $(document).ready(function(){
        $('#test_modal').modal('show');
    });

You can also close the modal popup manually by using the following JavaScript:


$('#test_modal').modal('hide')


Adjust Modal Width:
In order to adjust the modal width you have two options, Javascript or CSS. You can use the following JavaScript mentioned on GitHub:


   $('#test_modal').modal({
        backdrop: true,
        keyboard: true,
        show: false \remove this if you don't want it to show straight away
    }).css({
        width: 'auto',
        'margin-left': function () {
            return -($(this).width() / 2);
        }
    });

Or this CSS from StackOverflow:

body .modal-admin {
    //new custom width
    width: 750px;
    //must be half of the width, minus scrollbar on the left (30px)
    margin: -345px 0 0 -375px;
}

Show modal when the user scrolls past certain div
I’ve received another request on how to show the modal when a user scrolls to a certain div. The following should work, but please let me know if you have any issues.

/* Wait for document to load */
$(document).ready(function(){

$(window).scroll(function(){

//Retrieve scroll distance from top
var top = $(window).scrollTop();

//Retrieve the divs distance from top of page
var div_distance = $('my_div').offset().top;

//Use this if you want a bit of a variable distance, for instance if they scroll 150 pixels past the div
var buffer_distance = 150;

//Check if scrolled past div
if(top >= div_distance && top <= (div_distance + buffer_distance)){

//Show modal - you may want to add checks etc to see if it's already show
$('#test_modal').modal('show');

} else {

//Hide the modal, have scrolled past - you may want to add some checks to see if it's already hidden etc
$('#test_modal').modal('hide');                         
}        
}); 
});

Allow HTML String – Ruby on Rails

Just a quick post on how to prevent escaping for HTML within a string. Simply use html_safe?.

i.e. The following will show the bold tags as text:

<%= "GOOOOOOOGLE">

<b>GOOOOOOOGLE</b>

Whereas once we add html_safe the text will be displayed in bold:

<%= ("GOOOOOOOGLE").html_safe?>

GOOOOOOOGLE

PaperClip Issues – Ruby on Rails

I finally decided to replace all my existing code to handle images with Paperclip. I was following the screencast by Emerson Lackey, #134 Paperclip, however I ran into a couple of issues. Thankfully they were all very easily fixed, and probably wouldn’t have occurred at all if I’d simply watched the whole screencast instead of trying to rush on ahead.

Issue #1:
The first issue I encountered was that my asset fields weren’t appearing on the page:


      
        

I spent way too much time trying to work this one out, especially considering how obvious the solution is – the screencast is simply missing an “=” after the initial “<%" in "<% f.fields_for". Simply amend it as follows:


      
        

Issue #2:
The second one is actually encountered and addressed by Emerson himself. Unfortunately I started trying to find a solution before seeing his, so just in case someone else does a Google search I’ll include the issue here:

undefined method `symbolize_keys!' for "/system/assets/1/original/mack_truck.jpg?1329550205":String

     
       
       

The problem here is simply that the parenthesis are in the wrong place, simply amend your code as follows:

     
       
       

Anyway, hopefully this helps someone else out – let me know if there are any issues.

Update: Don’t name your model assets!
Unfortunately I followed the tutorials naming example and called my model Asset. While this may have been fine in earlier version of rails it causes quirky conflicts with the asset pipeline. I strongly encourage you to use a different name i.e. Uploads

Copying Text from Notepad++ to Microsoft Word

In the middle of doing up some documentation I realised that the formatting and colors aren’t kept when you copy and paste from Notepad++ to Microsoft Word. Luckily Google was able to help out by showing me default plugin that lets you keep all the syntax highlighting etc.

1: Hightlight any of the text you want copied
2: From the menu select Plugins > NppExport > Copy all formats to clipboard
3: Paste into Microsoft Word
Highlight code

Highlight code

Select NppExport

Select NppExport

Paste in Word

Paste in Word

And that’s it – all done!

Placing Multiple Button_To on the Same Line – Ruby on Rails

This is a problem that had me confused for an embarrassingly long time. Rails wraps button_to elements within a form and a div. Unfortunately this will take up 100% of the available width. Thankfully the solution is pretty straight forward – simply wrap buttons in a div and float them left like so:

    
'button'%>
'button' %>

A wrapper div isn’t strictly necessary however I usually add one just to be safe. While this will probably give a bunch of designers another reason to hate developers, I find that wrapping floated elements seems to save a lot of headaches when making changes down the track.

Using the code above you may also find that the divs aren’t filling as expected, simply add a div with a ‘clear:both’ style to the bottom of the wrapper:

'button'%>
'button' %>

Hopefully that doesn’t take anywhere near as long for you guys to figure out as it did me, time for a coffee break I think. Good luck!