Playing with jQuery and WordPress!

So I finally started playing with jQuery.. I know, I know, I’m a slowpoke. But now I’m pretty good at it, atleast at the newbie level! ^_^

I implemented a jQuery based search for my blog theme. Check it out! (You still have to press Enter key, I didn’t want auto search/search as you type)

Here is the main code. It’s kind of n00b-ish, but will optimize it as I learn more. (I’ve also used jquery-highlight plugin)

jQuery.noConflict();
jQuery(document).ready(function()
{
	var is_search_page = 0;
	var current_page = window.location.pathname;
	jQuery("#searchform").submit(function(e)
	{
		e.preventDefault();
		var searchtxt = jQuery("#searchform #s").val();
		jQuery("a#searchreset img#searchloader").show();
		jQuery.ajax(
		{
			url: blogurl + "/search/" + searchtxt,
			dataType: "html",
			type: "GET",
			error: function()
			{
				jQuery("#content").html("Error: Something went wrong.. Refresh Page.");
				jQuery("a#searchreset img#searchloader").hide();
			},
			success: function(data)
			{
				var searchresults = jQuery(data).contents().find("#content").html();
				jQuery("#content").hide();
				jQuery("a#searchreset img#searchloader").hide();
				jQuery("a#searchreset img#searchresetimg").show();
				jQuery("#content").html(searchresults);
				jQuery(".post-text").highlight(searchtxt);
				jQuery(".aside").highlight(searchtxt);
				jQuery("#content").fadeIn("slow");
				is_search_page = 1;
			}
		});
		return false;
	});

	jQuery("a#searchreset").click(function(e)
	{
		e.preventDefault();
		jQuery("a#searchreset img#searchresetimg").hide();
		jQuery("a#searchreset img#searchloader").show();
		if (is_search_page == 1)
		{
			jQuery.ajax(
			{
				url: current_page,
				dataType: "html",
				type: "GET",
				error: function()
				{
					current_page = blogurl;
					jQuery("a#searchreset img#searchloader").hide();
					jQuery("a#searchreset img#searchresetimg").show();
				},
				success: function(data)
				{
					var mainpagecont = jQuery(data).contents().find("#content").html();
					jQuery("#content").hide();
					jQuery("a#searchreset img#searchloader").hide();
					jQuery("#content").html(mainpagecont);
					jQuery("#content").fadeIn("slow");
					jQuery("#searchform #s").val("search..");
					jQuery("#searchform #s").blur();
					is_search_page = 0;
				}
			});
		}
	});
});

All it does is send a GET request to the Search Page, extract the contents from the #content DIV block from the response which replaces the contents in the #content DIV block in the current page. It also shows/hides the Reset icon. Clicking the Reset icon gets back the contents of the previous page. Not a neat way to do it, But it works!

2 Responses to “Playing with jQuery and WordPress!”


Comments are currently closed.