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

Monday 17 February 2014

Twitter Bootstrap single page website without the need for yet another plugin

The code below creates a page using Twitter Bootstrap. It contains one of those fashionable single page navigations. I needed to create one for a site I was developing for a client recently. When I started to look into it all the examples seemed to use a plugin. For performance purposes, I didn't want to use another plugin. Especially since jQuery already comes with the 'animate' class. See code below for solution.

<!DOCTYPE html>
<html>
  <head>
    <title>Single page website</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <style>  
    #about, #contact
    {
      padding-top:4em;
    }
    #contact
    {
      margin-bottom:40em;
    }
    </style>
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <div class="navbar navbar-default navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>        
        </div>
        <div class="navbar-collapse collapse">        
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#home">Home</a></li>
            <li ><a href="#about">About</a></li>
            <li><a href="#contact">Contact</a></li>
          </ul>
        </div><!-- nav-collapse -->
      </div><!-- container -->
    </div><!-- navbar -->

    <div id="home">
      <div class="row">
        <div class="container">
          <article class="col-md-4">
            <h2>Header 2</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid ad utilitatem tantae pecuniae? Age, inquies, ista parva sunt. Quibus ego vehementer assentior. Quae cum essent dicta, discessimus.</p>    
            <p>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</p>
          </article>
          <article class="col-md-4">
            <h2>Header 2</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid ad utilitatem tantae pecuniae? Age, inquies, ista parva sunt. Quibus ego vehementer assentior. Quae cum essent dicta, discessimus.</p>    
            <p>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</p>
          </article>
          <article class="col-md-4">
            <h2>Header 2</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid ad utilitatem tantae pecuniae? Age, inquies, ista parva sunt. Quibus ego vehementer assentior. Quae cum essent dicta, discessimus.</p>    
            <p>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</p>
          </article>
        </div><!-- container -->
      </div><!-- row -->
    </div><!-- section -->

    <div id="about">
      <div class="row">
        <div class="container">
          <figure class="col-md-4">    
            <img src="http://lorempixel.com/400/200/sports" alt="sports" class="img-responsive" />
            <figcaption>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</figcaption>
          </figure>
          <figure class="col-md-4">    
            <img src="http://lorempixel.com/400/200/sports" alt="sports" class="img-responsive" />
            <figcaption>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</figcaption>
          </figure>
          <figure class="col-md-4">    
            <img src="http://lorempixel.com/400/200/sports" alt="sports" class="img-responsive" />
            <figcaption>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</figcaption>
          </figure>
        </div><!-- container -->
      </div><!-- row -->
    </div><!-- section -->

    <div id="contact">
      <div class="row">
        <div class="container">
          <article class="col-md-6">
            <h2>Header 2</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid ad utilitatem tantae pecuniae? Age, inquies, ista parva sunt. Quibus ego vehementer assentior. Quae cum essent dicta, discessimus.</p>    
            <p>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</p>
          </article>
          <aside class="col-md-6">
            <h2>Header 2</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid ad utilitatem tantae pecuniae? Age, inquies, ista parva sunt. Quibus ego vehementer assentior. Quae cum essent dicta, discessimus.</p>    
            <p>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</p>
          </aside>
        </div><!-- container -->
      </div><!-- row -->
    </div><!-- section -->
    <footer class="navbar-default navbar-fixed-bottom">
      <div class="container">
        <a href="#home">Back to top</a>
      </div>
    </footer>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://code.jquery.com/jquery.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>  
    <script>
    (function()
    {
      $('.nav a, footer a').click(function()
      {
        var target = $(this).attr('href');
        var targetLoc = $(target).offset().top;      
        $('html, body').stop().animate(
        {
          scrollTop:targetLoc,
          easing:'swing'
        }, 1000);
        return false;
      });
    })();
    </script>
  </body>
</html>

Thursday 1 August 2013

HTML5 contenteditable save, re-save and save again

The HTML5 contenteditable attribute is really useful, but when you've got my typing skills, you'd really like to keep saving as you go. In the example below I'm writing to a text file for simplicity. I've got a few things going on.

  • If the text file exists or has data in there, I use it. Otherwise, the editable paragraph holds a default string.
  • I use a form submit to kick off a jQuery event.
  • The jQuery function calls a PHP script to write the contents of my editable paragraph to the file.

This way I can keep pressing the submit button as I go, which will just update the text file with the current editable paragraph contents.

Here's the code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Editable jQuery save</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<p id="content" contenteditable="true">
<?php
$text = file_get_contents('test.txt');
if(!empty($text))
{
echo $text;
}
else
{
echo 'Put some text here.';
}
?>
</p>
<form>
<input type="submit" />
</form>
<script>
(function()
{
$('form').submit(function()
    {
        $.post('set.php',
        {
            content:$('#content').text()
        }, function(data)
        {
        if(data)
        {
        console.log(data)
        }    
        });
        return false;
    });
})();
</script>
</body>
</html>

And set.php

<?php
if(isset($_POST['content']))
{
file_put_contents('test.txt', $_POST['content']);
}
else
{
echo 'write was not successful';
}
?>

Friday 12 July 2013

Form changer jQuery plugin

Websites I work on often include the need to add a login, password reset and self-registration form. This requirement can either take up too much space on the page, or require a refresh to load each form. They could all easily be put in a container like a div and called upon (or shown) only when needed. This is what I've done with the example below.
The 'data-location' anchor attributes must correspond to the form ID's they are requesting.
First, I've hidden all the things not required to be visible on load and just spaced the links out (in blue).
Second, I've created the container, forms and links I need (in red).
Third, I've called my plugin to handle the interaction (in green).
Below the HTML, I present the plugin code. There is a little catch all at the top, just in case anyone creates a container with either an ID, class or neither.
Enjoy!
<!DOCTYPE html>
<html lang="en">
<head>
<title>Form changer</title>
<style>
#formholder #resetpassword, #formholder #selfregister, #formholder a[data-location="login"]
{
display:none;
}
#formholder a
{
margin:0.2em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<div id="formholder">
<form id="login">
<p>Hello from login</p>
</form>
<form id="resetpassword">
<p>Hello from reset password</p>
</form>
<form id="selfregister">
<p>Hello from self-register</p>
</form>
<a href="#" data-location="login">Login</a><a href="#" data-location="resetpassword">Reset password</a><a href="#" data-location="selfregister">Self-register</a>
</div>
<script src="formchanger.plugin.js"></script>
<script>
(function()
{
$('#formholder a').formchanger();
})();
</script>
</body>
</html>

Now the plugin code:
(function($)
{
$.fn.formchanger = function()
{
id = $(this).parent().attr('id');
clas = $(this).parent().attr('class');
tag = $(this).parent().get(0).tagName;
if(id != null)
{
container = '#'+id;
}
else if(clas != null)
{
container = '.'+clas;
}
else
{
container = tag;
}
anchors = $(container).children('a');
forms = $(container).children('form');
$(this).click(function()
{
$(anchors).show();
$(forms).hide();
$(container+' #'+$(this).data('location')).show();
$(this).hide();
});
};
})(jQuery);

Monday 17 June 2013

Your first jQuery plugin

Here is a quick tutorial in how to create a jQuery plugin. Below is my basic page with a call to:
A file called 'first.plugin.js' containing the plugin (in red).
A call to a method called 'changetored' within that plugin (in blue).

<!DOCTYPE html>
<html lang="en">
<head>
<title>First jquery plugin test page</title>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
<style>
.red
{
color:red;
}
</style>
</head>
<body>
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
</body>
<!-- Call the plugin -->
<script src="first.plugin.js"></script>
<script>
(function()
{
/*
* changetored is a method declared in first.plugin.js
*/
$('p').changetored();
})();
</script>
</html>
Now for the plugin. Here is the file 'first.plugin.js'.

(function($)
{
$.fn.changetored = function()
{
/*
* In the context of a call like $('p').changetored();
* $(this) would become all paragraphs
*/
$(this).addClass('red');
};
})(jQuery);

Catching browser buttons

I was recently putting together an application. My test user did something I wasn't expecting. Rather than using the buttons within the application, he went for the browser buttons. It prompted me to provide a warning for the user that the application wouldn't work so well if he did this. See code below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test page</title>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<a href="index2.php">Go to page 2</a>
<script>
(function()
{
catchBrowser = true;

$('a').click(function()
{
catchBrowser = false;
});

$(window).bind('beforeunload', function()
{
if(catchBrowser == true)
{
return 'Please use only the buttons within the application pages.';
}
else
{
return;
}
});
})();
</script>
</body>
</html>

Wednesday 12 June 2013

Removing Twitter Bootstrap modal link outlines

Developers who use Twitter Bootstrap may have noticed a problem when they use the navigation controls to launch a modal. This could be a link at the top which launches a contact form for example. The problem is, that an outline to the link is left behind. I've seen a few 'solutions' to this on the web. None of which worked for me, because they were CSS solutions and the outline is created using JavaScript. So, here's what a link required to launch a modal looks like:
<a href="#myModal" data-toggle="modal">Launch modal</a>
And here is some coding for the modal:

<div id="myModal" class="modal hide fade" role="dialog">
  <p>Hello</p>
    <button class="btn btn-primary">Save</button>
  </div>
</div>
Now, at last is the solution. Because, JavaScript creates the problem, it's a good idea to use JavaScript (in my case jQuery) to resolve it. The code should look like this:

(function()
{
    $('a').data('toggle','modal').click(function()
    {
        $(this).css(
        {
            'outline':'none'
        });
    });
})();
Good luck.


Tuesday 2 October 2012

Presenting MySQL table data through PHP, JSON and jQuery

This may seem like a long way round to do something, but believe me, it has its benefits if you are trying to deliver an open systems approach to your development framework.

Let's say I have a MySQL database with table called chat. The chat table has 3 fields; userid, entry and datesaved.

I create a PHP script called jsonout.php which returns all rows of the chat table, thus:

<?php
$con = mysql_connect('localhost','root','');
mysql_select_db('test', $con);
$result = mysql_query('SELECT * FROM `chat`');
while($rows[] = mysql_fetch_assoc($result));
array_pop($rows);
mysql_close($con);
echo json_encode($rows);
?>

Notice the final line (in red) where I return a JSON encoded version of the resulting array.

Now my HTML page (below) can collect the JSON through jQuery and present the results on the page.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple JSON retrieval through jQuery</title>
<!--[if IE]>
 <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
 font:10px/15px Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
 google.load("jquery", "1");
</script>
</head>
<body>
<script>
(function()
{
 $.getJSON('jsonout.php', function(data)
 {
    $.each(data, function(i, items)
    {
      $('body').append('<p>'+items.userid+'</p>'+items.entry+'<p>'+items.datesaved+'</p>');
    });
 });
})();
</script>
</body>
</html>

Monday 1 October 2012

Simple JSON retrieval through jQuery

This page explains how to retrieve some simple JSON data and append it to a page. First the JSON through a script called jsonout.php

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}


Now the HTML with jQuery to retrieve and display it within the page.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple JSON retrieval through jQuery</title>
<!--[if IE]>
 <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font:10px/15px Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1"); 
</script>
</head>
<body>
<script>
(function()
{
$.getJSON('jsonout.php', function(data)
{
  $.each(data, function(key, val)
  {
    $('body').append('<p>'+key+':'+val+'</p>');
  });
});
})();
</script>
</body>
</html>

Monday 20 August 2012

Useful PHP quick test page

I developed this page a little while ago to do quick tests. Essentially, you just put items in the text box and press submit. The benefit of the page is that all the reloading is done for you. There is no need to keep using back or forward buttons. Just carry on making adjustments to your code and keep trying. The page will use the changes you make.

In the example below, I am outputing an md5 version of my input, but you can create your own functions and just replace the bit where md5 is called (highlighted in red).


<?php
$myname = $_GET ? html_entity_decode($_GET['myname']) : NULL;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<form>
<label for="myname">Type your string</label>
<input type="text" name="myname" id="myname" value="<?php  echo $myname; ?>" />
<button type="submit">Submit</button>
</form>
<p><?php echo $myname ? md5($myname) : NULL; ?></p>
<script>
(function()
{
  $('form').submit(function()
  {
    locStr = '<?php echo basename(__FILE__); ?>?str='+$('#myname').val();
    window.location.replace(locStr);
  }
})();
</script>
</body>
</html>

Wednesday 11 July 2012

HTML5 Audio Slideshow

Here, I've created a slideshow which syncs with a piece of audio. You can add different types of image and you can set the position in the audio when the image/slide appears. All free for you to play with.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>HTML5 Audio Slideshow</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
audio img
{
display:none;
}
#display_meta
{
width:300px;
min-height:225px;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
</head>
<body>
<br />
<img id="display_meta" src="1.png" /><br />
<audio id="greeting" controls="controls">
<source src="http://dl.dropbox.com/u/17154625/greeting.ogg" type="audio/ogg" />
<img src="jimmy.png" data-seconds="2" />
<img src="johnnie.png" data-seconds="4" />
<img src="julie.png" data-seconds="6" />
</audio>
<script>
var allImages = new Array(3);
var inc = 0, foundie = 0;
$('audio img').each(function()
{
allImages[inc] = new Array(3);
allImages[inc][0] = $(this).attr('src');
allImages[inc++][1] = $(this).data('seconds');
});
(function()
{
var displayTime = function()
{
var rVer = Math.round(greeting.currentTime);
foundie = giveBackImageName(rVer);
if(foundie != 0)
{
document.getElementById('display_meta').src = foundie;
}
}

var giveBackImageName = function(vr)
{
for (var i = 0; i < allImages.length; i++)
{
    if(allImages[i][1] == vr)
    {
    return allImages[i][0];
    }
}
return 0;
}
$('#greeting').bind('timeupdate', displayTime);
})();
</script>
</body>
</html>

Monday 27 June 2011

PHP Form, jQuery, working in IE

Some days, you start by saying, "'I'll just get this out of the way, then I can concentrate on something heavier". You then write code without testing because you know how it works, and apart from a little syntax change, you get it working fine. About 15 minutes. This was my experience with writing a page with a form. It stored the data in a text file, then updated the page tag with the new contents. It worked fine in Chrome and Firefox. Then the dreaded IE pulled me back. 3 hours later, I find the solution. Below are code examples to a common problem.
Create a html form.
On submission, write the contents of the form to a file.
Once the file has been updated, refresh a section showing the new content.

Here is the code for readdata.php. Notice the @ before file_get_contents. This suppresses a warning if the file does not already exist.

<?php
foreach (explode("\n", @file_get_contents('data.data')) as $value)
{
echo $value."<br />";
}
?>
Here is the code for writedata.php. Nothing particularly clever here.

<?php
file_put_contents('data.data', $_POST['stuff']."\n", FILE_APPEND);
?>
Now to the main page. A few of important items here:
  1. Only $.get works in IE .load doesn't.
  2. $.ajaxSetup({cache: false}) is also required for IE otherwise you get all sorts of content varients coming through.
  3. I used the jQuery Form Plugin from http://jquery.malsup.com/form/ It saves a lot of problems.


Have fun.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Read and write using jquery</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script type="text/javascript" src="jquery.form.js"></script>
<script>
$.fn.readStuff = function()
{
$.get('readdata.php', null, function(data)
{
    $('section').html(data);
});
$('#stuff').val('');
}
$(document).ready(function()
{
$.ajaxSetup({cache: false});
$('form').ajaxForm(function()
{
$(this).readStuff();
});
});
</script>
</head>
<body>
<h1>PHP and jQuery read/write test</h1>
<h2>Write data</h2>
<form action="writedata.php" method="POST">
<input type="text" name="stuff" id="stuff" />
<input type="submit" />
</form>
<h2>Read data</h2>
<section>
<?php
include 'readdata.php';
?>
</section>
</body>
</html>

Friday 10 June 2011

Fittext - Not bad

I came across a great new jQuery plugin today. Namely FitText. I've done dynamic text resizing myself before, but this seems like a better implementation. To test it, resize your browser.

See demo.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>FitText</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
h1
{
font-size:4em;
color:red;
line-height:1.5em;
}
h2
{
font-size:3em;
color:orange;
line-height:1em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script src="scripts/jquery.fittext.js"></script>
<script>
$(document).ready(function()
{
$('.fittext').fitText();
});
</script>
</head>
<body>
<header><h1 class="fittext">Header 1</h1></header>
<section id="mainContent">
<h2 class="fittext">It's all in the detail</h2>
<article>
<p class="fittext">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
</article>
</section>
<footer>Footer</footer>
</body>
</html>

Monday 4 April 2011

Hello jQuery Mobile

I've been  a bit quiet on the blog front over the last week because I've been knee deep in stuff. One of the things I've been working with is jQuery Mobile. A real solution for me. I didn't want to re-learn Java to create Android apps. I certainly didn't want to learn Objective-C for iPhone apps. I do want to use all my existing web and PHP skills to develop apps for mobile devices. jQuery Mobile suits this perfectly.

It's only really in alpha at the moment and be prepared to reconfigure everything you're done as each version changes, but it's already looking very good.

Below is my Hello World! page using jQuery Mobile.

See demo.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello jQuery Mobile</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.css" />
<script src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.js"></script>
</head>
<body>
<div data-role="page">
Hello jQuery Mobile
</div>
</body>
</html>

Monday 28 March 2011

Google TTS API for my paragraphs using HTML5, jQuery and PHP

Most of the credit for this post goes to Abu Ashraf Masnun for this post http://www.masnun.me/2009/12/14/googles-text-to-speech-api-a-php-wrapper-class.html
You'll need to take a copy of his code for this to work. Then you need to append the following lines to the end of the PHP (after his object declaration).
$tts = new TextToSpeech();
$tts->setText($_POST['text']);
$tts->saveToFile("masnun.mp3");

Once you've done this, you can create a HTML file like mine below. To use the page, click on the speaker icons.

Note:This will not work in rubbish browsers. For this you will need to change my HTML5 <audio> tag for something awful like the <object> tag.

Another note:The Google TTS has a 100 character limit.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Text to speech</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script>
var audioText = '<audio controls="controls" autoplay="autoplay">';
audioText += '<source src="masnun.mp3" type="audio/mpeg" />';
audioText += 'Your browser does not support the audio element.';
audioText += '</audio>';
$(document).ready(function()
{
$('.tts').each(function()
{
$(this).after('<a href="#" class="speaker"><img src="http://farm6.static.flickr.com/5091/5568186294_a396c02f4f_t.jpg" /></a>');
});
$('.speaker').click(function()
{
$.post('tts.php',
{
text:$(this).prev('p').text()
}, function(data)
{
$(this).after(audioText);
});
return false;
});
});
</script>
</head>
<body>
<section id="mainContent">
<p class="tts">Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante.</p>
<p class="tts">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
<p class="tts">Johnny Diamond. Peter Sam</p>
</section>
</body>
</html>

Wednesday 23 March 2011

Two by Two Layout

In this example I deliver to the user a browser divided by 4 sections of equal height and width. As the user resizes the browser, the page is refreshed so that the dimensions can be recalculated. You can also see how this would work with my previous blog post on font resizing. See http://effectivewebdesigns.blogspot.com/2011/03/resize-chosen-fonts-dynamically.html
I just chose not to include both entries because I like to keep my blog entries small.

See demo.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Two by Two Layout</title>
<!--[if IE]>
 <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style type="text/css">
body
{
font-family:Sans-serif;
background:#FFFFFF;
width:100%;
color:#525252;
line-height:1.5em;
}
#topLeft, #topRight, #bottomLeft, #bottomRight
{
color:#FFFFFF;
float:left;
padding:1em;
}
#topLeft
{
background:#000000;
text-align:right;
}
#topRight
{
background:#9CB82E;
}
#bottomLeft
{
background:#A69A00;
text-align:right;
}
#bottomRight
{
background:#B1009B;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
 google.load("jquery", "1");
 google.load("jqueryui", "1");
</script>
<script>
$(document).ready(function()
{
$('section').each(function()
  {
   $(this).height(($(window).height()*0.5)-32);
$(this).width(($(window).width()*0.5)-32);
  });
$("#topLeft p").position(
{
my: "right bottom",
at: "right bottom",
of: "#topLeft",
offset:"-20 -20"
});
$("#topRight p").position(
{
my: "left bottom",
at: "left bottom",
of: "#topRight",
offset:"20 -20"
});
$(window).resize(function() {
location.reload();
});
});
</script>
</head>
<body>
<section id="topLeft">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
</section>
<section id="topRight">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
</section>
<section id="bottomLeft">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
</section>
<section id="bottomRight">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
</section>
</body>
</html>

Resize chosen fonts dynamically

Again, I can't take much credit for this. The real credit goes to the author of this blog entry http://www.pukkared.com/2010/10/resizing-text-with-jquery-and-window-resize/. I have just made a few changes and calls for my own purposes. Namely, passing which fonts I would like to resize, what the original size should be and what size the page should be before resizing begins. Enjoy!

See demo.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic font resize</title>
<style>
body
{
font-family:Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
 google.load("jquery", "1");
 google.load("jqueryui", "1");
</script>
<script>
$.fn.resizeFonts = function(fontName, originalFontSize)
{
var originalWinWidth = $(window).width();
var ratioOfChange = 50;
$(fontName).css('font-size', originalFontSize);
$(window).resize(function()
{
var winWidth = $(window).width();
var widthDiff = winWidth - originalWinWidth;
if(widthDiff > 0)
{
var pixelsToIncrease = Math.round(widthDiff / ratioOfChange);
var newFontSize = originalFontSize + pixelsToIncrease;
$(fontName).css('font-size', newFontSize);
}
else
{
var pixelsToDecrease = Math.round(Math.abs(widthDiff) / ratioOfChange);
var newFontSize = originalFontSize - pixelsToDecrease;
$(fontName).css('font-size', newFontSize);
}
})
}
$(document).ready(function()
{
$(window).resize(function() {
if($(this).width() < 800)
{
$(this).resizeFonts('h1',20);
$(this).resizeFonts('p',10);
}
});
});
</script>
</head>
<body>
<h1>Big Mick's Recipe Book</h1>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
</body>
</html>

Friday 11 March 2011

Google Chart API - Not bad

Here, I have provided an example of implementing Google Charts. This should give you the confidence to try more out. I recommend that you visit http://code.google.com/apis/chart/docs/making_charts.html for more options.

See demo.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Google chart</title>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script>
$(document).ready(function()
{
$chartURL = 'http://chart.googleapis.com/chart?';
/* Add chart type */
$chartURL += 'cht=bhs';
/* add chart size */
$chartURL += '&chs=600x160';
/* add chart scale */
$chartURL += '&chxt=t&chxl=0:|Low+Value|High+Value';
/* add chart key */
$chartURL += '&chdl=Career|Happiness';
/* add chart colours */
$chartURL += '&chco=35D2AB|000000';
/* add chart values */
$chartURL += '&chd=t:';
$chartURL += '40,';
$chartURL += '80';
$('#chart').attr('src', $chartURL);
});
</script>
</head>
<body>
<img id="chart" />
</body>
</html>

Tuesday 1 March 2011

Yet another Slideshow

Below is the code for 2 pages with a slidehow. Why? I hear you ask, when there are so many slideshows out there. Why reinvent the wheel? Well the answer is because none of the wheels fit my needs.

I have been asked to look at re-doing a website which was a little dated. The site had an opportunity to use great pictures and there was a story behind each. If you want a picture which is partially covered by a semi-transparent comment, then there are plenty to be found.

If you want something which can choose different locations for you comments and style them as you please, then you will struggle to find something that suits your needs. So please feel free to use my code.

I have tried to keep the style information to a minimum.

See demo 1. See demo 2.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Slideshow</title>

<!--[if IE]>
 <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />

<style>
body
{
font-family:Sans-serif;
}
#slideshow #hiddenSlides
{
display:none;
}
#slideshow #slideWindow, #slideshow #textWindow
{
width:16em;
min-height:12em;
}
#slideshow #slideWindow img
{
width:100%;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
 google.load("jquery", "1");
 google.load("jqueryui", "1");
</script>
<script>
$.fn.slideFunction = function()
{
$theCurrent = $('#slideshow #hiddenSlides img.current');
$('#slideshow #textWindow').html($theCurrent.attr('alt'));
$('#slideshow #slideWindow img').fadeOut('fast');
$('#slideshow #slideWindow img').attr('src', $theCurrent.attr('src'));
$('#slideshow #slideWindow img').fadeIn('slow');
$theCurrent.removeClass('current');
if($theCurrent.next('img').length)
{
$theCurrent.next('img').addClass('current');
}
else
{
$('#slideshow #hiddenSlides img.first').addClass('current');
}
}
$(document).ready(function()
{
$(this).slideFunction();
setInterval(
function()
{
$(this).slideFunction();
}
,4000);
});
</script>
</head>
<body>
<section id="slideshow">
<section id="hiddenSlides">
<img src="http://farm3.static.flickr.com/2160/2271589215_935b5bc2ce_m.jpg" alt="<h3>Band of fog</h3><p>By Cath Redman</p>" class="first current" />
<img src="http://farm5.static.flickr.com/4140/4947943522_5ba46ef4df_m.jpg" alt="<h3>Wind farm</h3><p>Not mine. As soon as I find out who's it is, I'll reference it. I do know it's under the CC License</p>"  />
<img src="http://farm6.static.flickr.com/5054/5487320064_bb84f10fae_m.jpg" alt="<h3>Searchings for Snackers</h3><p>by Nomadic Lass</p>" />
<img src="http://farm6.static.flickr.com/5298/5486895517_1a74882a1e_m.jpg" alt="<h3>Point of View</h3><p>By Nicholas_T</p>" />
</section>
<section id="slideWindow"><img /></section>
<section id="textWindow"></section>
</section>
</body>
</html>



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Slideshow</title>
<style>
body
{
font-family:Sans-serif;
}
#slideshow
{
width:32em;
}
#slideshow #slideWindow, #slideshow #textWindow
{
display:inline;
}
#slideshow #hiddenSlides
{
display:none;
}
#slideshow #slideWindow, #slideshow #textWindow
{
width:16em;
min-height:12em;
}
#slideshow #slideWindow
{
float:left;
}
#slideshow #slideWindow img
{
width:100%;
}
h3
{
padding-left:14em;
}
p
{
padding-left:16.5em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
 google.load("jquery", "1");
 google.load("jqueryui", "1");
</script>
<script>
$.fn.slideFunction = function()
{
$theCurrent = $('#slideshow #hiddenSlides img.current');
$('#slideshow #textWindow').html($theCurrent.attr('alt'));
$('#slideshow #slideWindow img').fadeOut('fast');
$('#slideshow #slideWindow img').attr('src', $theCurrent.attr('src'));
$('#slideshow #slideWindow img').fadeIn('slow');
$theCurrent.removeClass('current');
if($theCurrent.next('img').length)
{
$theCurrent.next('img').addClass('current');
}
else
{
$('#slideshow #hiddenSlides img.first').addClass('current');
}
}
$(document).ready(function()
{
$(this).slideFunction();
setInterval(
function()
{
$(this).slideFunction();
}
,4000);
});
</script>
</head>
<body>
<section id="slideshow">
<section id="hiddenSlides">
<img src="http://farm3.static.flickr.com/2160/2271589215_935b5bc2ce_m.jpg" alt="<h3>Band of fog</h3><p>By Cath Redman</p>" class="first current" />
<img src="http://farm5.static.flickr.com/4140/4947943522_5ba46ef4df_m.jpg" alt="<h3>Wind farm</h3><p>Not mine. As soon as I find out who's it is, I'll reference it. I do know it's under the CC License</p>"  />
<img src="http://farm6.static.flickr.com/5054/5487320064_bb84f10fae_m.jpg" alt="<h3>Searchings for Snackers</h3><p>by Nomadic Lass</p>" />
<img src="http://farm6.static.flickr.com/5298/5486895517_1a74882a1e_m.jpg" alt="<h3>Point of View</h3><p>By Nicholas_T</p>" />
</section>
<section id="slideWindow"><img /></section>
<section id="textWindow"></section>
</section>
</body>
</html>

Tuesday 8 February 2011

Submit Form with Loader

I achieve 2 objectives with the form below.

The first is that I use jQuery to capture the user hitting the enter key after adding the password. By using jQuery, this works in all browsers.

The second thing I deliver is a 'loading...' image when the form has been submitted. It stays there until we have a result from the target PHP script, authenticate.php. Your authenticate.php could look something like this
<?php
echo 'Who are you?';
?>

You could also pass parameters to the PHP and do it properly. See http://effectivewebdesigns.blogspot.com/2010/10/send-form-information-to-php-through.html

BTW, you'll also have to create your own loading.gif

See demo.

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset="UTF-8">
<title>Submit Form with Loader</title>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script>
$(document).ready(function()
{
$('#pass').keyup(function(event)
{
if(event.keyCode == 13)
{
$("#sub").click();
}
});
$('#sub').click(function()
{
$('#formlogin').empty().html('<img src="loading.gif" />');
$.post('authenticate.php',
        {

        }, function(data)
        {
   $('#formlogin').empty().html(data);
        });
        return false;
});

});
</script>
</head>
<body>
<form id='formlogin'>
<input type='text' name='username' id='username' />
<input name='pass' id='pass' type='password' />
<input type='submit' value='login' name="sub" id="sub" />
</form>
</body>
</html>

Wednesday 2 February 2011

Simple layout #15

Here is another layout which uses jquery corners.

See demo.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Layout 15</title>
<!--[if IE]>
 <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<script src="http://www.google.com/jsapi"></script>
<style type="text/css">
*
{
 margin:0;
 padding:0;
}
body
{
 margin:0 auto;
 width:800px;
 margin-top:100px;
}
header
{
 float:left;
 color:#FF9200;
}
h1, h2, p
{
 font-weight:normal;
}
h1, h2
{
    font-family:Georgia, Times New Roman, Times, serif;  
    text-transform:uppercase;
color:#000000;
}
h1
{
    font-size:5em;
}
h2
{
    font-size:4em;
}
p
{
    font-family: Arial, Helvetica, sans-serif;
    font-style: normal;
    font-variant: normal;
    letter-spacing:0.1em;
    text-align:justify;
}
p
{
    font-size: 1.25em;
    margin-top: 1.25em;
    margin-bottom: 1.25em;
}
header p
{
 width:360px;
}
#tl
{
 float:right;
 width:400px;
 height:400px;
 background:#FF9200;
 color:#FFFFFF;
}
#tl p
{
 float:right;
 width:280px;
 padding-top:160px;
 padding-right:20px;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
 google.load("jquery", "1");
 google.load("jqueryui", "1");
</script>
<script type="text/javascript" src="http://github.com/malsup/corner/raw/master/jquery.corner.js"></script>
<script>
$(document).ready(function()
{
 $('#tl').corner('tl 400px');
});
</script>
</head>
<body>
 <header>
  <h1>header 1</h1>
  <h2>header 2</h2>
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.</p>
 </header>
 <div id="tl" class="">
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante.</p>
 </div>

</body>
</html>