jquery – CodeForest https://www.codeforest.net Wed, 08 Jan 2025 12:53:20 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.5 https://www.codeforest.net/wp-content/uploads/2017/06/cropped-Asset-3-32x32.png jquery – CodeForest https://www.codeforest.net 32 32 Laravel WYSIWYG editor https://www.codeforest.net/laravel-wysiwyg-editor?utm_source=rss&utm_medium=rss&utm_campaign=laravel-wysiwyg-editor https://www.codeforest.net/laravel-wysiwyg-editor#comments Tue, 25 Mar 2014 23:00:51 +0000 https://www.codeforest.net/?p=2168 I really like how Medium editor works, it brings a new way of adding and editing content and it really looks fresh, fast and intuitive.

Luckily, some great people wrote excellent jQuery plugins which allow us to integrate Medium style WYSIWYG editor to Laravel and that is the subject of today’s tutorial.

DemoSource files

I built a simple Laravel application which only have one entity for posts, just to demonstrate this integration. So, to get started, install new Laravel project to a folder of your choice:

[code lang=”php”]
composer create-project laravel/laravel laravel-medium –prefer-dist
[/code]

If you don’t know how to do this, please read my Getting started with Laravel tutorial.

You also need to alter the database credentials in /app/config/database.php file.

Ok, now we have a fresh new Laravel application, let’s start by creating a table for our Posts. I will do this manually. First, create a new migration:

[code lang=”php”]
php artisan migrate:make create_posts_table
[/code]

Now, open that file and paste this in:
/app/database/migrations/DATE_create_posts_table.php

[code lang=”php”]
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(‘posts’, function(Blueprint $table) {
$table->increments(‘id’);
$table->string(‘title’);
$table->text(‘body’);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop(‘posts’);
}
[/code]

And migrate the database:

[code lang=”php”]
php artisan migrate
[/code]

Ok, now we have a database table for our posts, let’s create a Post model:
/app/models/Post.php

[code lang=”php”]
class Post extends \Eloquent {
protected $guarded = array();

public static $rules = array(
‘title’ => ‘required’,
‘body’ => ‘required’
);
}
[/code]

Simple model with some simple validation rules in it.

Now, we will create a Posts controller, I will show the whole code at once and explain below:
/app/controllers/PostsController.php

[code lang=”php”]
class PostsController extends BaseController {

/**
* Post Repository
*
* @var Post
*/
protected $post;

public function __construct(Post $post)
{
$this->post = $post;
}

/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$posts = $this->post->all();

return View::make(‘posts.index’, compact(‘posts’));
}

/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
return View::make(‘posts.create’);
}

/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
$input = Input::all();
$validation = Validator::make($input, Post::$rules);

if ($validation->passes())
{
$this->post->create($input);
return Response::json(array(‘success’ => true, ‘errors’ => ”, ‘message’ => ‘Post created successfully.’));
}
return Response::json(array(‘success’ => false, ‘errors’ => $validation, ‘message’ => ‘All fields are required.’));
}

/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
$post = $this->post->findOrFail($id);

return View::make(‘posts.show’, compact(‘post’));
}

/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
$post = $this->post->find($id);

if (is_null($post))
{
return Redirect::route(‘posts.index’);
}

return View::make(‘posts.edit’, compact(‘post’));
}

/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
$input = array_except(Input::all(), ‘_method’);
$validation = Validator::make($input, Post::$rules);

if ($validation->passes())
{
$post = Post::find($id);
$post->update($input);

return Response::json(array(‘success’ => true, ‘errors’ => ”, ‘message’ => ‘Post updated successfully.’));
}

return Response::json(array(‘success’ => false, ‘errors’ => $validation, ‘message’ => ‘All fields are required.’));
}

/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
$this->post->find($id)->delete();

return Redirect::route(‘posts.index’);
}

public function upload()
{
$file = Input::file(‘file’);
$input = array(‘image’ => $file);
$rules = array(
‘image’ => ‘image’
);
$validator = Validator::make($input, $rules);
if ( $validator->fails()) {
return Response::json(array(‘success’ => false, ‘errors’ => $validator->getMessageBag()->toArray()));
}

$fileName = time() . ‘-‘ . $file->getClientOriginalName();
$destination = public_path() . ‘/uploads/’;
$file->move($destination, $fileName);

echo url(‘/uploads/’. $fileName);
}
}
[/code]

This is a pretty familiar controller with some gotchas. First, store and update methods are returning JSON, as they will be called using AJAX. There is also an upload method which will be used for image uploads to the editor.

Next, we need layouts, I created two, one will be used when we don’t need to use the editor:
app/views/layouts/layout.blade.php

[code lang=”php”]
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>@yield(‘title’) – Laravel Medium editor demo on Codeforest</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ url(‘css/medium-editor-insert.css’) }}">
<link rel="stylesheet" href="{{ url(‘css/style.css’) }}">
<style>
table form { margin-bottom: 0; }
form ul { margin-left: 0; list-style: none; }
.error { color: red; font-style: italic; }
body { padding-top: 20px; }
</style>
</head>

<body>

<div class="container">
@if (Session::has(‘message’))
<div class="flash alert">
<p>{{ Session::get(‘message’) }}</p>
</div>
@endif

@yield(‘main’)
</div>
</body>

</html>
[/code]

And another one which is similar, but is adding a partial view in footer, some needed CSS in header and injecting editors:
app/views/layouts/layout.editor.blade.php

[code lang=”php”]
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>@yield(‘title’) – Laravel Medium editor demo on Codeforest</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.1/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ url(‘css/medium-editor.css’) }}">
<link rel="stylesheet" href="{{ url(‘css/style.css’) }}">
<link rel="stylesheet" href="{{ url(‘css/themes/default.css’) }}">
<link rel="stylesheet" href="{{ url(‘css/medium-editor-insert.css’) }}">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<style>
table form { margin-bottom: 0; }
form ul { margin-left: 0; list-style: none; }
.error { color: red; font-style: italic; }
body { padding-top: 20px; }
</style>
</head>

<body>

<div class="container">
@if (Session::has(‘message’))
<div class="flash alert">
<p>{{ Session::get(‘message’) }}</p>
</div>
@endif

@yield(‘main’)
</div>
@include(‘partials.editor’)
</body>

</html>
[/code]

And we need the partial which will inject the proper scripts:
app/views/partials/editor.blade.php

[code lang=”php”]
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.1/js/bootstrap.min.js"></script>
<script src="{{ url(‘js/medium-editor.js’) }}"></script>
<script src="{{ url(‘js/medium-editor-insert.js’) }}"></script>
<script src="{{ url(‘js/main.js’) }}"></script>
[/code]

The code for medium wysiwyg editor and medium insert plugin can be obtained on Github.

Now, we need the views:
app/views/posts/index.blade.php

[code lang=”php”]
@extends(‘layouts.layout’)

@section(‘title’, ‘Posts’)

@section(‘main’)

<h1>All Posts</h1>

<p>{{ link_to_route(‘posts.create’, ‘Add new post’) }}</p>

@if ($posts->count())
<table class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Body</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>

<tbody>
@foreach ($posts as $post)
<tr>
<td style="width: 200px;">{{{ strip_tags($post->title) }}}</td>
<td>{{{ strip_tags(Str::words($post->body, 20)) }}}</td>
<td>{{ link_to_route(‘posts.show’, ‘View’, array($post->id), array(‘class’ => ‘btn btn-info’)) }}</td>
<td>{{ link_to_route(‘posts.edit’, ‘Edit’, array($post->id), array(‘class’ => ‘btn btn-info’)) }}</td>
<td>
{{ Form::open(array(‘method’ => ‘DELETE’, ‘route’ => array(‘posts.destroy’, $post->id))) }}
{{ Form::submit(‘Delete’, array(‘class’ => ‘btn btn-danger’)) }}
{{ Form::close() }}
</td>
</tr>
@endforeach
</tbody>
</table>
@else
There are no posts
@endif

@stop
[/code]

app/views/posts/create.blade.php

[code lang=”php”]
@extends(‘layouts.layout_editor’)

@section(‘title’, ‘Create Post’)

@section(‘main’)

<div class="error alert alert-danger"></div>
<div class="success alert alert-success"></div>

{{ Form::open(array(‘route’ => ‘posts.store’)) }}
<div class="title-editable" id="post-title"><h1>Enter post title</h1></div>
<div class="body-editable" id="post-body"><p>Enter post body</p></div>
{{ Form::submit(‘Save Post’, array(‘class’ => ‘btn btn-primary’, ‘id’ => ‘form-submit’)) }}

{{ Form::close() }}

@stop
[/code]

app/views/posts/edit.blade.php

[code lang=”php”]
@extends(‘layouts.layout_editor’)

@section(‘title’, ‘Edit post’)

@section(‘main’)

<div class="error alert alert-danger"></div>
<div class="success alert alert-success"></div>

{{ Form::open(array(‘method’ => ‘PATCH’, ‘route’ => array(‘posts.update’, $post->id))) }}
<div class="title-editable" id="post-title">{{ $post->title }}</div>
<div class="body-editable" id="post-body">{{ $post->body }}</div>
<input type="hidden" id="post-id" value="{{ $post->id }}">
{{ Form::submit(‘Update Post’, array(‘class’ => ‘btn btn-primary’, ‘id’ => ‘form-update’)) }}
{{ Form::close() }}

@stop
[/code]

app/views/posts/show.blade.php

[code lang=”php”]
@extends(‘layouts.layout_editor’)

@section(‘title’, ‘View Post’)

@section(‘main’)

<p>{{ link_to_route(‘posts.index’, ‘Return to all posts’) }}</p>
<div id="hideEditor" style="display:none;"></div>
<div id="post-title" class="title-editable">{{ $post->title }}</div>

<div id="post-body" class="body-editable">{{ $post->body }}</div>

@stop
[/code]

As you can see, there are no actual forms on create and edit view, just some markup. At the end, we need to add Javascript to make all this work:
public/js/main.js

[code lang=”js”]
// initializing editors
var titleEditor = new MediumEditor(‘.title-editable’, {
buttonLabels: ‘fontawesome’
});
var bodyEditor = new MediumEditor(‘.body-editable’, {
buttonLabels: ‘fontawesome’
});
$(function () {
// initializing insert image on body editor
$(‘.body-editable’).mediumInsert({
editor: bodyEditor,
images: true,
imagesUploadScript: "{{ URL::to(‘upload’) }}"
});
// deactivate editors on show view
if ($(‘#hideEditor’).length) {
$(‘.body-editable’).mediumInsert(‘disable’);
bodyEditor.deactivate();
titleEditor.deactivate();
}
});
// hiding messages
$(‘.error’).hide().empty();
$(‘.success’).hide().empty();

// create post
$(‘body’).on(‘click’, ‘#form-submit’, function(e){
e.preventDefault();
var postTitle = titleEditor.serialize();
var postContent = bodyEditor.serialize();

$.ajax({
type: ‘POST’,
dataType: ‘json’,
url : "{{ URL::action(‘PostsController@store’) }}",
data: { title: postTitle[‘post-title’][‘value’], body: postContent[‘post-body’][‘value’] },
success: function(data) {
if(data.success === false)
{
$(‘.error’).append(data.message);
$(‘.error’).show();
} else {
$(‘.success’).append(data.message);
$(‘.success’).show();
setTimeout(function() {
window.location.href = "{{ URL::action(‘PostsController@index’) }}";
}, 2000);
}
},
error: function(xhr, textStatus, thrownError) {
alert(‘Something went wrong. Please Try again later…’);
}
});
return false;
});

// update post
$(‘body’).on(‘click’, ‘#form-update’, function(e){
e.preventDefault();
var postTitle = titleEditor.serialize();
var postContent = bodyEditor.serialize();

$.ajax({
type: ‘PUT’,
dataType: ‘json’,
url : "{{ URL::action(‘PostsController@update’, array(Request::segment(2))) }}",
data: { title: postTitle[‘post-title’][‘value’], body: postContent[‘post-body’][‘value’] },
success: function(data) {
if(data.success === false)
{
$(‘.error’).append(data.message);
$(‘.error’).show();
} else {
$(‘.success’).append(data.message);
$(‘.success’).show();
setTimeout(function() {
window.location.href = "{{ URL::action(‘PostsController@index’) }}";
}, 2000);
}
},
error: function(xhr, textStatus, thrownError) {
alert(‘Something went wrong. Please Try again later…’);
}
});
return false;
});
[/code]

Actually, that’s it. I think that the above JavaScript code which make AJAX calls for create and update post is self explanatory.

The only thing left is adjusting the routes file:
app/routes.php

[code lang=”php”]
// upload image route for MediumInsert plugin
Route::any(‘upload’, ‘PostsController@upload’);
// resource routes for posts
Route::resource(‘posts’, ‘PostsController’);
[/code]

If you made it to here, you can now test all this in your browser…first run a server:

[code lang=”php”]
php artisan serve
[/code]

and point your browser to http://localhost:8000.

You can see all of this in action or download code from GitHub below:

DemoSource files

I hope you will find this useful in your next awesome Laravel 4 project. If you have any questions, do not hesitate to ask below in comments.

]]>
https://www.codeforest.net/laravel-wysiwyg-editor/feed 5
Creating mobile apps with jQuery Mobile – review https://www.codeforest.net/creating-mobile-apps-with-jquery-mobile-review?utm_source=rss&utm_medium=rss&utm_campaign=creating-mobile-apps-with-jquery-mobile-review Mon, 27 May 2013 20:41:34 +0000 https://www.codeforest.net/?p=1790 I got to read this excellent book from Packt publishing on creating mobile apps using Jquery Mobile.

When I started reading the book, I immediately realized that this book is not for total beginners. You have to have some prior knowledge of jQuery and PHP. Which is definitely great news.

You will need a web server to follow the tutorials from the book and I would recommend Wamp server for quick and easy start on Windows, and some kind of a text editor like Sublime Text or Notepad++.

Shane Gliser is a kind of author with first hand experience with jQuery Mobile, Shane’s primary passions are user experience and the mobile web. Shane began working with jQuery Mobile while it was still in the Alpha 2 phase and deployed American Century Investments’ mobile site while the framework was still in Beta 2.

As I said before, this book assumes that reader has HTML/CSS/jQuery and some PHP experience to better understand the examples and principles.

I really like how author address common issues that new users to jQuery mobile sometimes have. Things like adding custom icons to jQuery Mobile, Google Maps and form validation. Client-side templating is really a nice touch and well explained to the reader.

Book is a really great introduction in jQuery Mobile and starts with  prototyping, responsive design and HTML5 features like video, audio, geolocation and web storage which is all you need to build a modern mobile app.

Book also explain some PhoneGap basics which allows you to use several APIs and contain your mobile app in native container for several platforms.

All in all, a great jQuery Mobile book.

You can buy it from Packt Publishing or Amazon.

]]>
jQuery Calculus Game Tutorial – part 1 https://www.codeforest.net/jquery-calculus-game-tutorial-part-1?utm_source=rss&utm_medium=rss&utm_campaign=jquery-calculus-game-tutorial-part-1 Mon, 13 May 2013 20:34:44 +0000 https://www.codeforest.net/?p=1712 The idea behind this jQuery Calculus Game is fairly simple. You get a generated grid of number pairs and calculus task with some operand and anticipated result.

You then have to find pairs of numbers which makes the correct result.You start with 30 seconds at the beginning.

If you click on correct pairs, you get some bonus time, and if you click on wrong ones, you get some negative time.

If all that sounds confusing, here is a picture:

jQuery Calculus Game

I hope that this makes sense. The number 27 on the image is number of seconds remaining to solve the grid. It looks easy, as this part of the tutorial is for building a beginner’s level game which you can give your kids to enjoy.

So, let’s begin with some simple HTML markup for the game, so create a new game.php file and paste this markup in:

[code lang=”html”]
<!doctype html>
<html lang="en">
<head>

<title>Calculus Game by CodeForest</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="styles.css" />
<link href=’http://fonts.googleapis.com/css?family=Volkhov:400,700′ rel=’stylesheet’ type=’text/css’>

</head>

<body>

<div id="header">
<h1><a href=""><img src="calculus-logo.png" alt="Calculus Game by CodeForest" /></a></h1>
</div>

<div id="game_header">

<div id="task">
<span id="first">?</span>
<span id="operation"></span>
<span id="second">?</span>
&nbsp;=&nbsp;
<span id="result"></span>
</div>

<div id="timer" class=""></div>

</div>

<div id="grid"></div>
<script type="text/javascript" src="scripts/main.js"></script>
</body>
</html>
[/code]

As you already noticed, we need to create a scripts folder and put main.js file in it. This file will be used for all JavaScript needed for the game.

All the files will be available on GitHub, so there is no need to show the CSS here, you can make your own, or take mine from Github. All CSS, design and some grid generation were made by Zoran Jambor, so I really thank him for that.

Generating the grid

Our next task is to generate the grid, well not the HTML table, but an array of number pairs that will be used later to fill the table.

This is the function that is dealing with that part:

[code lang=”javascript”]
// gridDimension – dimension of the grid (if 6 is entered, grid will be 6*6)
// maxValue – max value for the result. Should not be less than 8.
// operation – ‘+’ or ‘-‘, the value is optional, if not entered, operation will be addition (+)
function generateGrid( gridDimension, maxValue, operation ) {

if (gridDimension % 2 != 0) {
gridDimension += 1; // as gridDimension can only be an even number
}
var grid = {
//Get random value for the result, based on maxValue
result : Math.ceil( Math.random() * maxValue ),

size : (gridDimension * gridDimension),

fields : [],

operation : operation || ‘+’
},

tempItem = ”;

//So that the problem doesn’t become too easy to solve
if ( grid.result < 8 ) grid.result += 6;

//Generating values for all fields in grid.
//Each pass generates 2 field values that when calculated give the result.
while ( grid.size ){

//Generate first random value
tempItem = Math.ceil( Math.random() * grid.result );

//Pair value is calculated based on operation
if ( grid.operation == ‘+’){

grid.fields.push( tempItem );
grid.fields.push( grid.result – tempItem );

} else {

tempItem += grid.result;
grid.fields.push( tempItem );
grid.fields.push( tempItem – grid.result);

}

grid.size -= 2;

}

//Randomize the field values
grid.fields.sort( function(){return 0.5 – Math.random()} );

return grid;

}
[/code]

The above code is really heavily commented, so I think everything is clear here. Basically, this function will be helping us with quickly generating the grid based on some parameters, which will come in handy in the later versions of the game, which will be even more dynamic.

Timer

Oh, I forgot to mention, there is a catch. For the game not to be too easy, the time to find all pairs is limited. So let us create a timer function which will be responsible for all time related tasks:

[code lang=”javascript”]
function timer(increment) {
// our HTML id for showing the time
var $timer = $(‘#timer’);

if(increment == 0) {
timer_start = start_time;
}

timer_start += increment;
$timer.html(timer_start);

// some colors on the timer
if( timer_start < 4 ) {

$timer
.removeClass(‘warning’)
.addClass(‘danger’);

} else if( timer_start < 8 ) {

$timer
.addClass(‘warning’);

} else {

$timer.
removeClass(‘warning danger’);

}

if(timer_start < 1) {
reset();
play();
}
}
[/code]

Ok, again pretty straightforward code. Let us write the reset function mentioned above, which will clear all elements, the intervals used and reset everything to it’s beginning state.

[code lang=”javascript”]
function reset(){
$(‘#grid, #operation, #result’).html(”);
$(‘#first, #second’).html(‘?’);
clearInterval(interval);
}
[/code]

The main play function

First, we will set some global variables which will be used through the game:

[code lang=”php”]
// global variables for the game
var interval,
start_time = 30, // time from which timer starts counting
bonusTime = 3, // bonus seconds for correct answer
punishmentTime = 3, // punishment seconds for wrong answer
gridSize = 6, // should be an even number, this is the side for our grid of numbers
maxValue = 10; // max result value

if (gridSize % 2 != 0) {
gridSize += 1; // if someone did not put an even number, correct it!
}
[/code]

Ok, I know you’re eager, here is our main play function, which is handling all, from generating the grid, drawing the table, setting timer and intervals, checking the results, adding bonus seconds, subtracting punishment time and announcing the winner or resetting the game if time runs out.

[code lang=”javascript”]
/**
* Main method for playing
*/
function play() {

// choose operation randomly
if (Math.ceil(Math.random() * 2) == 2) {
operand = ‘+’;
} else {
operand = ‘-‘;
}
// generating our grid
var result = generateGrid(gridSize, maxValue, operand);

// filling the table with grid values
var html = ‘<table><tbody><tr>’, fieldsLength = result.fields.length;
for ( var i = 0; i < fieldsLength; i++) {
attr = ‘cell’;

html += ‘<td id="cell’ + (i + 1) + ‘">’ + result.fields[i] + ‘</td>\n’;

if ((i + 1) % gridSize == 0) {
html += ‘</tr><tr>’;
}
}

html += ‘</tr></tbody></table>’

//this will be better solved next time
$(‘#grid’).append(html);
$(‘#operation’).append(result.operation);
$(‘#result’).append(result.result);

// core gaming
timer(0);

// setting the interval to 1 second
interval = setInterval(function() {
timer(-1);
}, 1000);

var check = false, first = 0, second = 0, firstID = ”, secondID = ”;

//Cache often used selectors.
var animationTimeout = 200, $first = $(‘#first’), $second = $(‘#second’), hasWon = (gridSize * gridSize) / 2, correctPairs = 0;

$(‘#grid’).find(‘td’).each(
function() {

$(this).click(
function() {

if (!check) {

first = $(this).html();
$(this).addClass(‘active’);
$first.html(first);
firstID = $(this).attr(‘id’);
check = true;

} else {

second = $(this).html();
$second.html(second);
secondID = $(this).attr(‘id’);

if (result.operation == ‘+’) {

tempResult = parseInt(first)
+ parseInt(second);

} else {

tempResult = parseInt(first)
– parseInt(second);

}

// correct
if (tempResult == result.result
&& firstID != secondID) { // also checking for 2 clicks on the same cell

$(‘#’ + firstID + ‘, #’ + secondID).html(
‘X’).addClass(‘success’);

//Timeout to allow success animation to finish.
setTimeout(function() {

$(‘#’ + firstID + ‘, #’ + secondID)
.removeClass(‘success active’)
.addClass(‘completed’);

}, animationTimeout);

timer(bonusTime); // bonus time

// incrementing number of correct pairs
correctPairs += 1;
// did we won the game?
if (correctPairs == hasWon) { //yes, we did!!!
reset();
alert(‘You won the game!’);
}

} else {

timer(-punishmentTime); // punishment

$(‘#’ + firstID + ‘, #’ + secondID)
.addClass(‘active error’);

setTimeout(function() {

$(‘#’ + firstID + ‘, #’ + secondID)
.removeClass(‘error active’);

}, animationTimeout);

check = false;

}

$second.html(‘?’);
$first.html(‘?’);
check = false;
}
});
});
}
[/code]

The code above is also commented heavily, so I hope that you can find your way through it.

There is one more thing to do and that is to call the play method on document.ready:

[code lang=”javascript”]
$(document).ready(function(){
play();
});
[/code]

You can see the demo or download files below:

Source filesDemo

What’s next

This concludes the first part of jQuery Calculus game tutorial. In the next part we will go further with difficulty levels, rounds, scores and high scores tables.

I am eager to see what will come out of this.

If you have any questions, do not hesitate to ask in the comments section below!

]]>
10 new jQuery and CSS3 Resources https://www.codeforest.net/10-new-jquery-and-css3-resources?utm_source=rss&utm_medium=rss&utm_campaign=10-new-jquery-and-css3-resources https://www.codeforest.net/10-new-jquery-and-css3-resources#comments Mon, 02 Apr 2012 20:35:11 +0000 https://www.codeforest.net/?p=1248 HTML5, CSS3 and jQuery are the most hyped tools of 2012. Most people call this new hype HTML5, but HTML5 is only a a new set of standards, semantics and rules for coding website markup that help us interact with the newest native browser features.

What makes really cool effects on today’s websites is not a markup, but set of new innovative CSS3 rules and a bunch of awesome JavaScript (read jQuery) code.

CSS3 Responsive slider without JavaScript

csscience

Yeah, that’s not a mistake. Ian Hansonn (@teapoted) at CSScience made a responsive CSS3 slider using radio buttons and no JavaScript.

As Ian says:

The actual slider is much like any JavaScript slider. It floats all of the content areas (articles) next to each other. And then hides the overflow. We then animate the margin of the inner div, so if we have 5 articles, moving the left-margin -100% would give us the second article.

You can see the demo on CSScience.

Sigma.js – lightweight JavaScript library to draw graphs

sigma

Sigma.js is an open-source lightweight JavaScript library to draw graphs, using the HTML canvas element. It has been especially designed to:

  • Display interactively static graphs exported from a graph visualization software
  • Display dynamically graphs that are generated on the fly

You can see a bunch of cool visualization examples on Sigma.js example page, so go and check it out.

jQuery Scroll Path

jQuery Scroll Path

jQuery Scroll Path is a plugin that lets you define your own custom scroll path. What this means exactly is best understood by checking out the demo. The plugin uses canvas flavored syntax for drawing paths, using the methods moveTo, lineTo and arc. To help with getting the path right, a canvas overlay with the path can be enabled when initiating the plugin.

Scrolling can be done with the mouse wheel, up/down arrow keys and spacebar. The space bar scrolls faster than the arrow keys, and holding shift while pressing space will scroll backwards. A custom scroll bar is also included, which allows click and drag scrolling. The scroll bar is enabled by default.

Flickrush – jQuery Flicker plugin

Flickrush

Flickrush is a jQuery plugin designed to make it quick and easy to add your flickr photo stream to any web page with minimal effort. Fully customisable you can choose the number of photos, randomise the ordering and style to fit in with any blog or web page.

Demo can be seen here and documentation can be seen on Flickrush main page.

Timeline

timeline

Timeline plugin is used to create beautifully crafted timelines that are easy, and intuitive to use.

Timeline is also great for pulling in media from different sources. It has built in support for pulling in Tweets and media from Twitter, YouTube, Flickr, Vimeo, Google Maps and SoundCloud. More media types will be supported in the future.

You can see and download it on Timeline.

iPicture

iPicture

iPicture is a jQuery Plugin to create interactive pictures with extra descriptions presented as tooltips.

It comes with a wizard to help you generate the effect as soon and as easily as possible simply by dragging and droping. More info on plugin’s page.

RainBow – JavaScript Code Syntax Highlighter

Rainbow

Rainbow is a code syntax highlighting library written in Javascript. It was designed to be lightweight (1.4kb), easy to use, and extendable.

It is completely themable via CSS. Rainbow on its own is very simple. It goes through code blocks, processes regex patterns, and wraps matching patterns in tags. All the theming is left up to CSS.

cssFx.js – CSS3 property polyfill

cssFx is a standalone polyfill that inserts the vendor-specific CSS3 properties necessary for old and new browsers. This saves you tons of time, maintenance, and bandwidth.

Features that are supported includes: box shadows, border radius, multiple columns, border image, RGBA, transforms, keyframes, transitions (and properties inside transitions), flexible box, gradients, and a ton of other useful things (like opacity, ellipsis, and inline-block).

Browser support includes: Firefox 3+, Chrome 1+, Internet Explorer 6+, Safari 3+, Opera 9+.

jQuery Retina plugin

retina

Images that aren’t retina optimized look blown up and fuzzy on retina devices. At the moment, this is only the new iPad (aka, iPad 3), iPhone 4 and 4S. However, more and more devices will soon be retina enabled; from Android and Windows mobile devices, to OSX and Windows desktops.

Until more desktops have retina displays, this requires a client side solution. jQuery Retina plugin will swap out the image source for an image that is sized for retina displays.

The plugin will check if the device retina enabled, and if so, swap out the image with one that is twice as large.

While calling the plugin, the user can also specify if they want to check if the file exists or not.

Plugin and demo can be seen on official jQuery Retina plugin page.

Webshims lib

webshims lib

Webshims Lib is a modular capability-based polyfill-loading library, which focuses on accurate implementations of stable HTML5 features, so that developers can write modern, interoperable and robust code in all browsers. It is built on top of jQuery and Modernizr.

The more features a browser supports natively, the more lightweight webshims will be. It works in IE6+, Firefox 3.6+, Safari 5.0.3+, Safari for iOS 5+, Chrome 16.0+, Opera 11.6+.

]]>
https://www.codeforest.net/10-new-jquery-and-css3-resources/feed 3
jQuery Mobile 1.0 Final Released https://www.codeforest.net/jquery-mobile-1-0-final-released?utm_source=rss&utm_medium=rss&utm_campaign=jquery-mobile-1-0-final-released https://www.codeforest.net/jquery-mobile-1-0-final-released#comments Thu, 17 Nov 2011 20:29:28 +0000 https://www.codeforest.net/?p=1133 jQuery Mobile has been a great mobile framework from the beginning in summer of 2010. I always liked the framework for its simplicity and a plethora of documentation.

Being it on site documentation or resources and tutorials that could be found around the internet (even here you can find jQuery Mobile Tutorial: Basics and jQuery Mobile Advanced Tutorial), this framework is very well documented.

Coming out of their mouth:

Equally as important, we set out to make this framework easy for developers to get up and running fast, with a minimal learning curve.

So let’s see what is new.

ThemeRoller

ThemeRoller is a web-based tool that makes it super simple to create custom themes without writing a single line of CSS. Drag and drop colors to create your masterpiece, then share it via URL or download a ZIP file with your custom theme stylesheet, ready for production (or additional tweaking).

jQuery Mobile ThemeRoller

Yeah, it is that awesome. Enough said, go and check it out on ThemeRoller page.

The main man behind the ThemeRoller is Tyler Benzinger, a guy who was borrowed from Adobe.

When you create your awesome jQuery Mobile Theme, just download the zip archive with compressed theme file (for production) as well as the uncompressed ones (for tweaking). Inside an archive there is also an index.html file as sample of how your theme is working on jQuery Mobile elements. Awesome.

One more thing: the complete source code for the new jQuery Mobile ThemeRoller tool is open source under the standard jQuery project licenses for you to improve, remix and build into your apps. The core tool is designed to work completely client-side to make it easy to drop into your code — only the download and sharing features require a bit of PHP. Go forth and fork it on GitHub.

Performance

The team spent hours and hours optimizing the framework and gain 30-50% better performance than RC2 release. They are already working on improving touch event responsiveness, page transition and scrolling smoothness and other important factors in upcoming releases.

Resources

As I said earlier, jQuery Mobile has a huge community that has been incredibly active writing plugins and extensions, building frameworks and tools that enhance the library, and writing tons of articles and tutorials. There are now 8 books on jQuery Mobile and many more in the works.

All resources can now be found in brand new Resources page.

Other news

There are other great stuff on their pages like new documentation site, quick start guide, the oft-requested data-attribute reference, a set of global configuration test pages that let your easily preview key settings, a PhoneGap tips page, detailed documentation on the experimental touchOverflow feature, info on how to access new features of the fixed toolbars, and much more.

Since jQuery 1.7 was just recently released and has some significant changes (and improvements), only 1.6.4 is officially supported at this time. 1.7 support is planned in version 1.1.

All you need to get going is putting this 3 lines inside your HTML file:

[code lang=”html”]

[/code]

Platforms

jQuery Mobile has broad support for the vast majority of all modern desktop, smartphone, tablet, and e-reader platforms. In addition, feature phones and older browsers are supported because of their progressive enhancement approach.

Get the full list of supported platforms

I am excited with this release, as this is a full-blown HTML 5 Mobile framework.

What do you think? Share your comments below…

]]>
https://www.codeforest.net/jquery-mobile-1-0-final-released/feed 3
jQuery UI 1.8 – The User Interface Library for jQuery – Book Review https://www.codeforest.net/jquery-ui-1-8-the-user-interface-library-for-jquery?utm_source=rss&utm_medium=rss&utm_campaign=jquery-ui-1-8-the-user-interface-library-for-jquery Thu, 10 Nov 2011 21:09:37 +0000 https://www.codeforest.net/?p=1126 I deal with jQuery a lot in my line of work and have a great amount of understanding how jQuery works as well as how jQuery UI is helping with its great widgets.

When I started reading this great book, I realized that there is plenty new things I can learn out of it.

On the very beginning of the book, there is a detailed introduction in jQuery and jQuery UI 1.8 set up. Everything is very well explained, from download to setting up a development environment, and is easily followed even by inexperienced developers.

Dan Wellman, the author, has been writing computer-related articles, tutorials, and reviews for around eight years and is rarely very far from a keyboard of some description. This is his fourth book.

The second chapter jumps into the explaining how jQuery UI works and is very detailed. The core css functionality is explained as well as theming, theme overriding, theme switching, widgets and how to create them, avoiding collisions etc.

After that book is explaining all the widgets in stunning details and great screenshots. Every single option for every widget is explained and show hot it affects the result. The detailed explaining and screenshots is what makes this book stand out.

In the last part, jQuery UI effects are explained with same amount of enthusiasm as in previous chapters. Even the advanced effects are shown like:

  1. Blind
  2. Clip
  3. Drop
  4. Explode
  5. Fold
  6. Puff
  7. Pulsate
  8. Scale
  9. Slide

What I really like about this book is that it gave me the big picture and then gently followed me to the tiniest details in jQuery UI. All examples used in a book can really be used in a real life scenarios, and that is really something.

If you are interested in jQuery UI this book is definitely a must read. Even advanced developers can learn something out of it.

You can buy this book at Amazon: jQuery UI 1.8: The User Interface Library for jQuery or Packt Publishing

]]>
jQuery Mobile RC1 released – what’s new? https://www.codeforest.net/jquery-mobile-rc1-released-whats-new?utm_source=rss&utm_medium=rss&utm_campaign=jquery-mobile-rc1-released-whats-new https://www.codeforest.net/jquery-mobile-rc1-released-whats-new#comments Fri, 30 Sep 2011 05:57:10 +0000 https://www.codeforest.net/?p=1066 jQuery Mobile is a unified user interface system across all popular mobile device platforms, built on the rock-solid jQuery and jQuery UI foundation. Its lightweight code is built with progressive enhancement, and has a flexible, easily themeable design.

It has been around for some time and is accepted by many developers for its simplicity and device support.

The biggest challenge in developing such a system is browser support. There are many mobile browsers available and it isn’t easy to cope with that. But jQuery Mobile keeps everything up to date.

Browser support

I will just mention the newest additions to the browser/OS list and that is Nokia Meego. jQuery Mobile supports even iOS 5 Beta OS.

To view the extensive list of browsers go to jQuery Mobile browser support page.

Collapsibles

A few final tweaks are made to the collapsible and accordion widget that really improves the visual design. First off, they removed the extra button style around the +/1 icons which made this look too much like a separate interactive element (it’s not, the whole bar is clickable) and cleaned up the visual appearance.

jQuery Mobile Collapsibles

iOS5 Transitions

The new iOS5 page transitions and true fixed headers have been improved significantly since Beta 3 but this feature is off by default for now. jQuery Mobile is now using a 3D transform CSS rule reduce page rendering artifacts which could cause memory use issues on very complex pages so you may need to override this selectively.

Download builder

This is one of the mos impressive features in jQuery Mobile RC1.

Download builder will let you build a custom version of jQuery Mobile to only include the parts you need. For example, you could just use the core files to add Ajax-based navigation with pushState and leverage some of the touch events and other utilities with a very lightweight build (roughly 10k). Or, you could add in specific UI widgets like form elements, listviews, etc. to create an optimized build. We’re aiming to have a download builder tool launch as part of 1.0 final in some form.

ThemeRoller tool

This tool will help developers make new themes a breeze. The beta of the ThemeRoller tool is only announced now and it will be available in a few weeks.

Team announced that this tool will make it drop-dead-simple to build a stunning theme in minutes.

Search input: Icon themeable and retina-ready

jqm search icon

The small search icon in the search input was the last standalone icon that hadn’t yet been integrated into the standard icon sprite.This icon is fully themable and includes the HD retina icon version too. To do this, jQuery Mobile team had to place the icon inside the standard icon disc so the appearance is a bit different, but it now matches the rest of the UI system. Note that this is add though a CSS technique that isn’t supported by IE 6-7 so in those browsers, the icon won’t appear.

Deprecated features

Deprecated re-named page events – the deprecated beforechangepage (now pagebeforechange), changepage (now pagechange), and changepagefailed (now pagechangefailed) events references have been dropped in preparation for the 1.0 release. See the events API documentation and commit log for more info.

Removed support for the alpha signature of $.mobile.changePage() in preparation for 1.0. Folks now how to use the signature that requires the toPage (url or element) as the first arg, and options object as the 2nd. See the events API documentation and commit log for more info.

Removed deprecated navigation related properties: $.mobile.updateHash$.mobile.urlstack. See commit log for details.

Removed the deprecated $.fixedToolbars property in preparation for 1.0. See commit log for details.

Removed $.mobile.pageLoading() call which was replaced by $.mobile.showPageLoadingMsg()and $.mobile.hidePageLoadingMsg()

List of changes in changelog is impressive like adding jQuery 1.6.4 support, Hardware acceleration of elements within the page in touch-enabled scenarios to prevent hidden elements (not just blinking, but flat-out disappearing) in iOS5, enable forms to submit to the same page and many more.

Team announced a few days ago that the Nokia Meego implementation was the easiest ever.

What are you waiting for? To test this awesome new release (I know I will), just include this in your files:

[code lang=”javascript”]

[/code]

Do you use jQuery Mobile in your line of work? Please share your thoughts in comment section and use the links below to spread the wrod abut this great release.

]]>
https://www.codeforest.net/jquery-mobile-rc1-released-whats-new/feed 2
jQuery Mobile First Look book review https://www.codeforest.net/jquery-mobile-first-look-book-review?utm_source=rss&utm_medium=rss&utm_campaign=jquery-mobile-first-look-book-review Sun, 18 Sep 2011 20:37:43 +0000 https://www.codeforest.net/?p=1020 I opened a new category on this blog where you will be able to find different Reviews. I will be reviewing books, frameworks, tools and other resources inside this category.

First in a series of book reviews is excellent book from Packt Publishing called jQuery Mobile First Look written by Giulio Bai.

I read the e-book version of the publication.

Who is this book for?

This book is targeted at jQuery users who want to enter the exciting world of mobile web development, as it is said in the preface. This is entirely true. To follow the book, all you need is a basic knowledge of jQuery Framework and a web browser.

Review

At the very beginning of the book, there is a nice introductory chapter about jQuery Mobile and comparison with similar frameworks. It shows the reader how to download and use jQuery Mobile.

Of course, all source code for the book is available for the download from the publisher’s site, which is very nice, as you don’t have to rewrite all the code found in the book.

There is a small problem with first few chapters as they are written for jQuery Mobile Alpha 2 which was the latest release at the publishing date (June 2011). jQuery Mobile is at Beta 2 phase now and some things have changed. Nevertheless, reader can easily download Alpha 2 release from the CDN or make few simple tweaks to the code. This really is not a problem. Writing a book on a pre-release version of software is always hard.

What I really liked in this book is how it explains the use of common tools which help developer to see what is happening behind the scenes. There is a nice explanation of using FireBug to debug your code. Book also mentions FireQuery, A FireBug extension for jQuery.

jQuery Mobile First Look is handling all the basic elements of jQuery Mobile like Pages, Buttons, Lists, Forms, Toolbars. It also explains how to change a look and feel of this elements as well as how to use different themes.

Conclusion

This book offers the very basics of a powerful jQuery Mobile framework. But, it is intended to jQuery developers to get to know the relevant first things. More advanced topics are just briefly explained.

I hope that this book will be updated in the second edition in the first 2 chapters so it reflects the changes in jQuery Mobile core.

If you are new to jQuery Mobile, this book is a must have. After reading it, you will be able to start making mobile web applications.

This book is available from:
Packt Publishing
Amazon

]]>
jQuery Mobile Advanced Tutorial – RSS reader app https://www.codeforest.net/jquery-mobile-advanced-tutorial-rss-reader-app?utm_source=rss&utm_medium=rss&utm_campaign=jquery-mobile-advanced-tutorial-rss-reader-app https://www.codeforest.net/jquery-mobile-advanced-tutorial-rss-reader-app#comments Tue, 23 Aug 2011 06:59:38 +0000 https://www.codeforest.net/?p=970 Today’s tutorial is going to show you how you can use jQuery Mobile with PHP, MySQL and a bit of AJAX to build a small mobile web application.

At the end of this tutorial you will know how to add new RSS feed name and url into the database, how to delete the record from the database, how to fetch and parse a RSS feed and show its results inside jQuery Mobile list view.

If you are not familiar with jQuery Mobile, I suggest you read my jQuery Mobile basic tutorial and then come back.

So, let’s start. Many things in our RSS reader application will take place inside our index.php file. The front page of the application will have links for creating new RSS feed and Read existing feeds.

First of all we need a database table to store our feeds in. Create one using this SQL code:

[code lang=”sql”]
CREATE TABLE IF NOT EXISTS `demo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM
[/code]

Now, I will create a db.php which will have a database connection and some basic functions for database handling. Create folder named inc and put your db.php file in it with this code pasted:

[code lang=”php”]
/*** mysql hostname ***/
$hostname = ‘localhost’;

/*** mysql username ***/
$username = ‘root’;

/*** mysql password ***/
$password = ”;

$dbname = ‘demo’;

try
{
mysql_connect($hostname, $username, $password);
mysql_select_db($dbname);
}
catch (Exception $e)
{
// normally we would log this error
echo $e->getMessage();
}

function db_select_list($query)
{
$q = mysql_query($query);
if (!$q) return null;
$ret = array();
while ($row = mysql_fetch_array($q, MYSQL_ASSOC)) {
array_push($ret, $row);
}
mysql_free_result($q);
return $ret;
}

function db_select_single($query)
{
$q = mysql_query($query);
if (!$q) return null;
$res = mysql_fetch_array($q, MYSQL_ASSOC);
mysql_free_result($q);
return $res;
}
[/code]

This is a pretty basic code for connecting and fetching records from our database.

To keep things organized, I will put my header section inside external PHP file. Inside inc folder create file named header.php, then paste this in the header file:

[code lang=”php”]




Codeforest jQuery Mobile Tutorial



[/code]

This is basic HTML 5 header with included jQuery and jQuery Mobile.

Now create a file in your root directory and name it index.php and paste this in it:

[code lang=”php”]

Welcome!

CodeForest



[/code]

Save everything and try it in your browser. Pretty cool.

As you can see our links to other pages look like anchor links. I am going to have multiple pages inside my index.php file and that is the way to link to them.

Now paste this whole code inside index.php overwriting the previous code:

[code lang=”php”]

Welcome!

CodeForest

Add New RSS Feed

Back



Codeforest

RSS Feeds

Back

CodeForest



[/code]

Above code is pretty simple. There are 3 pages, the indexPage, addFeedPage and readFeedPage. As we firstly have to add some feeds to read, let me show you how to do it.

As you can see, the AddNewFeedPage is basically a form for collecting New feed data (Feed name and Feed URL). Open your index.php in browser and click on Create New Feed link. You should see the form.

Now, add this JavaScript code directly before the closing body tag in your index.php file:

[code lang=”javascript”]

[/code]

Above code is catching Submit button click event and making an AJAX call to addFeed.php file which will handle the database writing. Create an addFeed.php file and paste this in:

[code lang=”php”]
getMessage();
}
[/code]

We are including our database file, sanitizing user input (you should never trust user entered data and always sanitize it!) and finally writing our entry in database. Now, go and add your RSS feed and save it. Make sure the feed URL is correct.

Now go back to your home page and click on Read RSS feeds link. You should see a feed name you just entered. Let me show you how to fetch and parse this feed.

Create a file named feed.php in your root directory and paste this in:

[code lang=”php”]
feedData.php in your root folder and paste this in:

[code lang=”php”]




[/code]

This code is rendering the view. First we check if feed is valid and if it is parsing it using SimpleXMLElement. Go ahead and try it. If everything worked, you should see 10 titles from the feed which are links to the actual articles.

If something is wrong with the feed format and it is not in RSS feed format, you will get a nice message.

Notice the Delete button on top right. It is used so you can delete the feed you are viewing from the database. Create deleteFeed.php and paste the code for deleting in:

[code lang=”php”]

I hope that this tutorial showed how easy it is to build mobile web applications using jQuery Mobile, PHP and MySQL.

Do you like jQuery Mobile? Are you using it or plan to use it? Do not hesitate to discuss in our comment section below. And if you have any questions, I will gladly answer them.

Stay tuned.

]]>
https://www.codeforest.net/jquery-mobile-advanced-tutorial-rss-reader-app/feed 11