Archive for the ‘jQuery’ Category

Google maps, mySQL locations, PHP service

Wednesday, May 4th, 2016

HTML:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="dealers.css">
</head>
    <body>
        <div class="row mapSection">
            <div class="col-xs-12">

                <div id="map"></div>
                <div id="panel">
                    <div id="entryRow">
                        <div><select id="locationSelect" style="width:100%;visibility:hidden"></select></div>
                        <input type="text" id="addressInput" />
                        <select id="radiusSelect">
                            <option value="5" selected>5 miles</option>
                            <option value="25" selected>25 miles</option>
                            <option value="100">100 miles</option>
                            <option value="200">200 miles</option>
                            <option value="500">500 miles</option>
                        </select>
                        <input type="text" id="find" value="Search"/>
                        <input type="button" id="refresh" value="redo Search"/>
                    </div>
                    <ul class="resultDealers">
                    </ul>
                </div>

            </div>
        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
        <script src="https://maps.googleapis.com/maps/api/js?key=***YOUR*KEY*HERE***" type="text/javascript"></script>
        <script type="text/javascript" src="Maps.js"></script>
    </body>
</html>

CSS:

body {
  font-family: sans-serif;
  margin: 0px;
  padding: 0px;
}
#map,
#panel {
  height: 500px;
  float: left;
}
#map {
  width: 60%;
}
#entryRow {
  margin: 0 0 0 15px;
}
#panel {
  width: 40%;
}
.resultDealers {
  padding: 0;
  margin: 15px;
  overflow: scroll;
  height: 420px;
}
.resultDealers li {
  list-style-type: none;
  border-left: 1px solid;
  border-top: 1px solid;
  border-right: 1px solid;
  padding: 10px;
}
.resultDealers li:last-child {
  border-bottom: 1px solid;
}
.highlightDealer {
  background: #E8E8E8;
}
.markerBox {
  cursor: pointer;
}
.markerBox:hover {
  background: #E3F4F9;
}
#panel .feature-filter label {
  width: 130px;
}
p.attribution,
p.attribution a {
  color: #666;
}
#find {
  background: #DEDCDC;
  border: 1px solid gray;
  width: 65px;
  padding: 2px;
  text-align: center;
  font-weight: bold;
  cursor: pointer;
  margin-left: 15px;
}
#find:hover {
  background: #F9F4F4;
}
#radiusSelect {
  margin-left: 15px;
}
#addressInput {
  float: left;
  margin-left: 5px;
  padding-left: 10px;
  width: 65px;
}
#locationSelect {
  margin: 10px 5px;
  width: 95% !important;
}

JavaScript:

/* ---------  Start Maps.js  --------- */

Maps Module
//Usage: Maps.init();

Maps = (function ( window, google ) {

	var map,
		markers = [],
		infoWindow,
		locationSelect;

	var load = function load () {
			map = new google.maps.Map(document.getElementById("map"), {
				center: new google.maps.LatLng(40, -100),
				zoom: 4,
				mapTypeId: 'roadmap',
				// scrollWheel: false,
				// zoomControl: false,
				streetViewControl: false,
				rotateControl: false,
				fullscreenControl: false,
				navigationControl: false,
				scaleControl: false,
				// draggable: false,
				mapTypeControl: false,
				mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
		});
		infoWindow = new google.maps.InfoWindow();

		locationSelect = document.getElementById("locationSelect");
		locationSelect.onchange = function() {
			var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
			if (markerNum != "none"){
				google.maps.event.trigger(markers[markerNum], 'click');
			}
		};

		refreshMap();

		google.maps.event.addListener(map, 'zoom_changed', function() {
			//$('#radiusSelect option:selected').next().attr('selected', 'selected');
			//console.log(map.getCenter());
			//searchLocationsNear (map.getCenter());
		});

	}

	var bindInfoWindow = function bindInfoWindow ( marker, map, infoWindow, html ) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    var refreshMap = function refreshMap () {
    	if(navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {

				var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

				var geocoder = new google.maps.Geocoder();

				geocoder.geocode({ 'latLng': latLng}, function (results, status) {
					if (status == google.maps.GeocoderStatus.OK) {

						for ( var j = 0; j < results[0].address_components.length; j++ ) {
							for ( var k = 0; k < results[0].address_components[j].types.length; k++ ) {
								if ( results[0].address_components[j].types[k] == "postal_code" ) {
									zipcode = results[0].address_components[j].short_name;
								}
							}
						}

						document.getElementById("addressInput").value = zipcode;
						searchLocations();
					} else {
						console.log("Geocoding failed: " + status);
					}
				});
			});
		}
	}

	var downloadUrl = function downloadUrl ( url, callback ) {
		var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
		request.onreadystatechange = function() {
			if ( request.readyState == 4 ) {
				request.onreadystatechange = doNothing;
				callback(request.responseText, request.status);
			}
		};

		request.open('GET', url, true);
		request.send(null);
	}

	var searchLocations = function searchLocations () {
		var address = document.getElementById("addressInput").value;
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode({address: address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
	  			searchLocationsNear(results[0].geometry.location);
			} else {
	  			alert(address + ' not found');
			}
		});
	}

	var clearLocations = function clearLocations() {
		infoWindow.close();
		for (var i = 0; i < markers.length; i++) {
			markers[i].setMap(null);
		}
		markers.length = 0;

		locationSelect.innerHTML = "";
		var option = document.createElement("option");
		option.value = "none";
		option.innerHTML = "See all results:";
		locationSelect.appendChild(option);
	}

	var searchLocationsNear = function searchLocationsNear ( center ) {
		clearLocations();

		var radius = document.getElementById('radiusSelect').value;
		var searchUrl = '/dealers.php?lat=' + center.lat() + '&lng=' +  center.lng() + '&radius=' + radius;
		downloadUrl( searchUrl, function(data) {
			var xml = parseXml(data);
			var markerNodes = xml.documentElement.getElementsByTagName("marker");
			var bounds = new google.maps.LatLngBounds();
			for (var i = 0; i < markerNodes.length; i++) {
				var id = markerNodes[i].getAttribute("id");
				var name = markerNodes[i].getAttribute("name");
				var address = markerNodes[i].getAttribute("address");
				var city = markerNodes[i].getAttribute("city");
				var state = markerNodes[i].getAttribute("state");
				var zip = markerNodes[i].getAttribute("zip");
				var url = markerNodes[i].getAttribute("url");
				var email = markerNodes[i].getAttribute("email");
				var distance = parseFloat(markerNodes[i].getAttribute("distance"));
				var latlng = new google.maps.LatLng(
					parseFloat(markerNodes[i].getAttribute("lat")),
					parseFloat(markerNodes[i].getAttribute("lng")));

				createOption(name, distance, i);
				createMarker(id, latlng, name, address, city, state, zip, url, email);
				bounds.extend(latlng);
			}
			map.fitBounds(bounds);
			locationSelect.style.visibility = "visible";
			locationSelect.onchange = function() {
			 var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
			 google.maps.event.trigger(markers[markerNum], 'click');
			};
		});
	}

	var createMarker = function createMarker ( id, latlng, name, address, city, state, zip, url, email ) {
		var html = "<div class='marker-" + id + "'><b>" + name + "</b> <br/>" + address +  "<br/>" + city + " " + state + ", " + zip + "<br />" + url + "<br /><a href='mailto:" + email + "'>" + email + "</a></div>";
		var marker = new google.maps.Marker({
			map: map,
			position: latlng
		});
		google.maps.event.addListener(marker, 'click', function() {
			//infoWindow.setContent(html);
			//infoWindow.open(map, marker);
			$("li[class*='marker-']").removeClass('highlightDealer');
			$("li.marker-" + id).addClass('highlightDealer');
			window.location.href = "#marker-"+ id;
			window.scrollTo(0, 0);

			map.setZoom(16);
			map.setCenter(marker.getPosition());
		});
		markers.push(marker);

		$("#panel ul").append("<li class='markerBox marker-" + id + "'><a name='marker-" + id + "'></a><b>" + name + "</b><br/>" + address +  "<br/>" + city + " " + state + ", " + zip + "<br />" + url + "<br /><a href='mailto:" + email + "'>" + email + "</a></li>");
		$('.marker-' + id).on('click', function() {
			$("li[class*='marker-']").removeClass('highlightDealer');
			$("li.marker-" + id).addClass('highlightDealer');
			map.setZoom(16);
			map.setCenter(marker.getPosition());
		});
	}

	var createOption = function createOption ( name, distance, num ) {
		var option = document.createElement("option");
		option.value = num;
		option.innerHTML = name + "(" + distance.toFixed(1) + ")";
		locationSelect.appendChild(option);
	}

	var parseXml = function parseXml(str) {
		if (window.ActiveXObject) {
			var doc = new ActiveXObject('Microsoft.XMLDOM');
			doc.loadXML(str);
			return doc;
		} else if (window.DOMParser) {
			return (new DOMParser).parseFromString(str, 'text/xml');
		}
	}

    function doNothing() {}

	$('#find').on('click', function() {
		$('#panel ul').empty();
		searchLocations();
	});
	$('#addressInput').on('click', function () {
		$(this).val('');
	});
	$('#radiusSelect').on('change', function () {
		$('#panel ul').empty();
		searchLocations();
	});
	$('#refresh').on('click', function () {
		var bounds = map.getBounds();
		var ne = bounds.getNorthEast(); // LatLng of the north-east corner
		var sw = bounds.getSouthWest(); // LatLng of the south-west corder

		var nw = new google.maps.LatLng(ne.lat(), sw.lng());
		var se = new google.maps.LatLng(sw.lat(), ne.lng());
		console.log('nw: ' + nw);
		console.log('se: ' + se);
		//searchLocationsNear();
		//searchLocations();
	});

	return {
		load: load
	}

})( window, google );

$(function(){
    loadModules.start();
})

var loadModules = loadModules || {};
loadModules.start = function(){
    // Maps module init
    Maps.load();
};
/* ---------  End Maps.js --------- */

PHP:

<?php
    header("Access-Control-Allow-Origin: *");
    $servername = "***Your*DB*URL***";
    $username = "***Your*DB*USERNAME***";
    $password = "***Your*DB*PASS***";
    $dbname = "***Your*DB*NAME***";

    // Get parameters from URL
    $center_lat = $_GET["lat"];
    $center_lng = $_GET["lng"];
    $radius = $_GET["radius"];

    // Start XML file, create parent node
    $dom = new DOMDocument("1.0");
    $node = $dom->createElement("markers");
    $parnode = $dom->appendChild($node);

    // Opens a connection to a mySQL server
    $connection=mysql_connect ($servername, $username, $password);
    if (!$connection) {
      die("Not connected : " . mysql_error());
    }

    // Set the active mySQL database
    $db_selected = mysql_select_db($dbname, $connection);
    if (!$db_selected) {
      die ("Can\'t use db : " . mysql_error());
    }

    // Search the rows in the markers table
    $query = sprintf("SELECT id, name, address, city, state, zip, url, email, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM dealers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
      mysql_real_escape_string($center_lat),
      mysql_real_escape_string($center_lng),
      mysql_real_escape_string($center_lat),
      mysql_real_escape_string($radius));
    $result = mysql_query($query);

    $result = mysql_query($query);
    if (!$result) {
      die("Invalid query: " . mysql_error());
    }

    header("Content-type: text/xml");

    // Iterate through the rows, adding XML nodes for each
    while ($row = @mysql_fetch_assoc($result)){
        $node = $dom->createElement("marker");
        $newnode = $parnode->appendChild($node);
        $newnode->setAttribute("id", $row['id']);
        $newnode->setAttribute("name", $row['name']);
        $newnode->setAttribute("address", $row['address']);
        $newnode->setAttribute("city", $row['city']);
        $newnode->setAttribute("state", $row['state']);
        $newnode->setAttribute("zip", $row['zip']);
        $newnode->setAttribute("url", $row['url']);
        $newnode->setAttribute("email", $row['email']);
        $newnode->setAttribute("lat", $row['lat']);
        $newnode->setAttribute("lng", $row['lng']);
        $newnode->setAttribute("distance", $row['distance']);
    }

    echo $dom->saveXML();

?>

Javascript Module of jQuery extensions, example: animateRotate

Wednesday, November 25th, 2015
/* ---------  Start jquery.extensions.module.js  --------- */

// jquery extensions Module

(function ( $ ) {

	$.fn.animateRotate = function(angle, duration, easing, complete) {
		var args = $.speed(duration, easing, complete);
		var step = args.step;
		return $(this).each(function(i, e) {
		   	args.complete = $.proxy(args.complete, e);
		    args.step = function(now) {
		    	$.style(e, 'transform', 'rotate(' + now + 'deg)');
		    	if (step) return step.apply(e, arguments);
		    };

		    $({deg: 0}).animate({deg: angle}, args);
		});
	}

// method/extension #2 goes here, and so on...

})( window.jQuery );

/* ---------  End jquery.extensions.module.js --------- */

Google Maps API v3 load array of locations, detect ip and zoom, generate list by distance to locations

Friday, October 23rd, 2015

In the template or HTML:

<div id="container">
<div class="row mapSubNav">
<div class="col-xs-6">
<div class="mapNavLeft">Find a Store</div>
</div>
<div class="col-xs-6 mapNavRight">
<a id="mapView">Map View</a> | <a id="listView">List View</a>
</div>
</div>
<div class="row">
<div class="col-xs-12 noPad">
<div id="floating-panel">
<input id="findAddress" name="findAddress" type="textbox" value="Find a Store - City, State, Zip">
<select id="findRadius">
<option value="13" selected="selected">radius</option>
<option value="12">5 miles</option> <!-- 4 miles -->
<option value="11">10 miles</option> <!-- 8 miles -->
<option value="10">15 miles</option> <!-- 16 miles -->
</select>
<input id="findSubmit" type="submit" value="Find a shop" class="btnLeft">
</div>
<div class="sideBar">
<div class="closeBtn">x</div>
<h3>Our Stores:</h3>
</div>
<div id="map"></div>
<div id="outputList"></div>
</div>
</div>
</div><strong>
</strong>

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&amp;amp;key=**YOUR_KEY_HERE**"</script>;
<script type="text/javascript" src="${sharedResourcePath}/js/locations.js"</script>;
<script type="text/javascript" src="${sharedResourcePath}/js/maps-module.js"</script>;

Locations array example:

var DEALERS = (function() {
var image = '../images/marker.png';

var locations = [
['location name 1',32.215143,-90.151818,map,image,'detailed description'],
['location name 2',47.336401,-116.888100,map,image,'detailed description'],
['location name 3',33.755219,-90.715672,map,image,'detailed description'],
['location name 4',33.646063,-87.058802,map,image,'detailed description'],
['location name 5',48.548468,-117.909399,map,image,'detailed description']
];
})();

 

MAPS MODULE JS:

MAPMOD = (function( window, google, DEALERS ) {

 var gmarkers = [],
 infos = [],
 map = {},
 whichMap = "";

 var init = (function init () {
 
 if( !document.getElementById("map") ) { return; }

 whichMap = $('#map').attr("data-map-type");

 switch( whichMap ) {
 case "dealer":
 var myOptions = {
 //center: new google.maps.LatLng(37.4419, -122.1419),
 zoom: 4,
 mapTypeId: google.maps.MapTypeId.ROADMAP,
 scrollwheel: false,
 disableDefaultUI: true,
 draggable: false,
 scaleControl: false,
 zoomControl: false
 };
 initDealerDetail(myOptions);
 break;

 case "all": 
 var myOptions = {
 zoom: 4,
 mapTypeId: google.maps.MapTypeId.ROADMAP,
 scrollwheel: false
 };
 allDealers(myOptions);
 break;
 }
 });

 var allDealers = (function allDealers (myOptions) {
 
 map = new google.maps.Map( document.getElementById("map"), myOptions );

 setMarkers( map, DEALERS.locations );

 var geocoder = new google.maps.Geocoder();

 var US = {
 NorthEast: {
 lat: 49.38,
 lng: -66.94
 },
 SouthWest: {
 lat: 25.82,
 lng: -124.39
 }
 }
 
 var USbounds = new google.maps.LatLngBounds(new google.maps.LatLng(US.SouthWest.lat, US.SouthWest.lng),
 new google.maps.LatLng(US.NorthEast.lat, US.NorthEast.lng));

 map.fitBounds(USbounds);
 //var USrect = new google.maps.Rectangle({map:map, bounds: USbounds});

 $('#findSubmit').on('click', function() {
 geocodeAddress(geocoder, map);
 });

 $("#findAddress").on("click", function() {
 $(this).val("");
 })

 $("#mapView").on("click", function() {
 $("#outputList").hide();
 $("#map").show();
 })
 
 $("#listView").on("click", function() {
 $("#map").hide();
 $("#outputList").show();
 })
 
 document.onkeydown=function() {
 if(window.event.keyCode=='13') {
 $('#findSubmit').click();
 }
 }

 geolocate(geocoder, map);
 });

 var geolocate = (function geolocate (geocoder, map) {

 // Try HTML5 geolocation.
 if (navigator.geolocation) {

 //var address = document.getElementById('findAddress').value ? document.getElementById('findAddress').value : {};

 navigator.geolocation.getCurrentPosition(function(position) {
 var pos = {
 lat: position.coords.latitude,
 lng: position.coords.longitude
 };

 //infoWindow.setPosition(pos);
 //infoWindow.setContent('Location found.');
 document.getElementById('findAddress').value = pos.lat + " " + pos.lng;
 $('#findRadius').val(8);
 geocodeAddress(geocoder, map);

 //map.setCenter(pos);
 //map.setZoom(9);
 }, function() {
 handleLocationError(true, infoWindow, map.getCenter());
 });
 } else {
 // Browser doesn't support Geolocation
 handleLocationError(false, infoWindow, map.getCenter());
 }
 });

 var initDealerDetail = (function initDealerDetail (myOptions) {

 map = new google.maps.Map( document.getElementById("map"), myOptions );

 setMarkers( map, DEALERS.locations );

 var lat = parseFloat( $('#map').attr("data-map-lat") );
 var lng = parseFloat( $('#map').attr("data-map-lng") );

 var pos = {
 lat: lat,
 lng: lng
 };

 map.setCenter(pos);
 map.setZoom(15);
 map.panBy(-250, 0);
 });
 
 function handleLocationError(browserHasGeolocation, map, pos) {
 map.setPosition(pos);
 map.setContent(browserHasGeolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser doesn\'t support geolocation.');
 }
 
 function geocodeAddress(geocoder, resultsMap) {
 
 var address = document.getElementById('findAddress').value;
 
 var radius = parseInt($( "#findRadius option:selected" ).val());
 if(isNaN(radius)){ radius = 8; }

 geocoder.geocode({'address': address}, function(results, status) {
 
 if (status === google.maps.GeocoderStatus.OK) {
 resultsMap.setCenter(results[0].geometry.location);

 var marker = new google.maps.Marker({
 map: resultsMap,
 position: results[0].geometry.location,
 });

 closest = findClosestN(results[0].geometry.location,10);

 // get driving distance
 closest = closest.splice(0,10);
 $('#findAddress').val(results[0].formatted_address);

 calculateDistances(results[0].geometry.location, closest,10);
 
 resultsMap.setZoom(radius);
 
 } else {
 $('#findAddress').val("No results. Please try again");
 }
 });
 }
 
 function findClosestN(pt,numberOfResults) {
 var closest = [];

 for (var i=0; i<gmarkers.length;i++) {
 gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers[i].getPosition());
 
 //$('#findAddress').val("process " + i + ":" + gmarkers[i].getPosition().toUrlValue(6) + ":" + gmarkers[i].distance.toFixed(2) + "<br>");
 //gmarkers[i].setMap(null);
 closest.push(gmarkers[i]);
 }
 closest.sort(sortByDist);
 return closest;
 }

 function sortByDist(a,b) {
 return (a.distance- b.distance)
 }

 function calculateDistances(pt,closest,numberOfResults) {
 $('#outputList').html('');
 var service = new google.maps.DistanceMatrixService();
 var request = {
 origins: [pt],
 destinations: [],
 travelMode: google.maps.TravelMode.DRIVING,
 unitSystem: google.maps.UnitSystem.IMPERIAL,
 avoidHighways: false,
 avoidTolls: false
 };
 
 for (var i=0; i<closest.length; i++) request.destinations.push(closest[i].getPosition());
 service.getDistanceMatrix(request, function (response, status) {
 if (status != google.maps.DistanceMatrixStatus.OK) {
 alert('Error was: ' + status);
 } else {
 var origins = response.originAddresses;
 var destinations = response.destinationAddresses;
 
 var results = response.rows[0].elements;
 for (var i = 0; i < numberOfResults; i++) {

 $('#outputList').append('\
 <label for="dealer' + i + '" class="col-xs-8 dealerItem">\
 <input type="radio" value="' + closest[i].title + '" name="dealers" id="dealer' + i + '">\
 <span>' + closest[i].title + '</span>\
 <span class="dealerAddress">' + destinations[i] + '</span>\
 </label>\
 <div class="col-xs-4 distance">' + results[i].distance.text + '</div>');
 }
 }
 });
 }
 
 function setMarkers(map,locations) {
 
 var marker, i
 
 for (i = 0; i < locations.length; i++) { 
 
 var loan = locations[i][0],
 lat = locations[i][1],
 lng = locations[i][2],
 add = locations[i][5];
 
 latlngset = new google.maps.LatLng(lat, lng);

 var marker = new google.maps.Marker({ 
 map: map,
 title: loan ,
 position: latlngset,
 icon: './images/tp.png'
 });

 gmarkers.push(marker);
 
 //console.log(marker.getPosition());
 //map.setCenter(marker.getPosition());
 
 var content = add;
 var infowindow = new google.maps.InfoWindow();
 
 google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
 
 return function() {
 
 /* close the previous info-window */
 closeInfos();
 
 infowindow.setContent(content);
 infowindow.open(map,marker);
 
 /* keep the handle, in order to close it on next click event */
 infos[0]=infowindow;
 
 };

 })(marker,content,infowindow)); 
 
 }
 }
 
 function closeInfos() {
 
 if(infos.length > 0) {
 
 /* detach the info-window from the marker ... undocumented in the API docs */
 infos[0].set("marker", null);
 
 /* and close it */
 infos[0].close();
 
 /* blank the array */
 infos.length = 0;
 }
 }
 
 return {
 init: init
 }

})(window, google, window.DEALERS);
MAPMOD.initMap();

jQuery Regex Selector examples ^=Starts with, $=Ends with, is of Class [0-9] threw in an encodeURIComponent for kicks

Monday, August 12th, 2013

Obviously, if your jQuery version is up to date, you should use .on
but I was fixing one of our sites that is stuck in 1.5,
so here are some examples using .delegate and .bind
The regex blocks are the same either way:

$.fn.popSubject = function() {
var menuA = $(“#askMenuA option:selected”).text();
var menuB = $(“#askMenuB option:selected”).text();
$(‘input[id$=”hiddensubject”]‘).val(menuA + ” – ” + menuB);
}

$(‘[id^=rn_FormSubmit_][id$=_Button]‘).bind(‘click’, ‘button’, function(event){
//Call Omniture when SA initial form submitted
s_exp_trackClick( this, ‘a’,”support.faq.sa.first.” + encodeURIComponent($(“#askMenuA option:selected”).text()) );
});

$(“body”).delegate(‘[id^=rnDialog1_Button][id$=[0-9]]‘, ‘click’, function(event){
//Call Omniture when SA dialog box submitted
s_exp_trackClick( this, ‘a’,’support.faq.sa.pop.’+ encodeURIComponent($(“#askMenuB option:selected”).text()) );
});

load external JavaScript from within another JS

Monday, February 25th, 2013

Of course there are many ways to do this, js loading libraries/managers,
what if you can’t get to the html though, and want to have control over all JS functions externally,
say from the JS files alone on a separate CDN… a JS ‘include’ is what we need…
since jQuery 1.8, in order to get a callback to take action in the even that the file doesn’t load,  a ton of different solutions that used to work, no longer do, and with jsonp or script type calls, the error function doesn’t even get called, here’s to trying to get one to work:

complete, success, .error, and on and on…

but no, solution:

var jqxhr = $.ajax({
url: “http:/…”,
dataType: ‘script’,
crossDomain: true,
timeout: 5000,
cache: false
})
//.done(function() { alert(“success”); })
.fail(function() { ajaxFailure(); })
//.always(function() { alert(“complete”); });

 

reference: http://api.jquery.com/jQuery.ajax/

jQuery .hover change div background-position example

Wednesday, November 16th, 2011

example for reference:

$(“#formButtonSubmit“).hover(function(){
$(this).css({
backgroundPosition: ‘0px 0px’
});
}, function(){
$(this).css({
backgroundPosition: ‘0px 30px’
});
});

Secure HTML form example using PHP htmlentities, passing a token PHP, AJAX submission via jQuery

Wednesday, September 21st, 2011

<? php
// form page (index.php): initialize a session so that we can set a unique, random, encrypted value to a user session
session_start();
$token = md5(uniqid(rand(), true));
$_SESSION[‘token’] = $token;
? >
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<script src=”js/jquery.js” type=”text/javascript”></script>
<script src=”js/jquery.validation.js” type=”text/javascript”></script>
<script src=”js/registerSubmit.js” type=”text/javascript”></script>
</head>
<body>
<!– The Form –>
<form id=”topForm” name=”topForm” method=”post”>
<input type=”hidden” name=”token” id=”token” value=”<? php echo $token; ? >” />
<input name=”emailAddress” id=”emailAddress” value=”Email address” onclick=”if( this.value == ‘Email address’ ){ $(this).val(”); }” onblur=”if( this.value == ”){ $(this).val(‘Email address’); }” />
</form>
</body>
</html>

// The jquery.validation.js class uses a regular expression to stop the process if the email entered isn’t acceptable

;(function($) {
$.validation = {};
$.extend( $.validation, {
email:function(email) {
var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if ( filter.test(email) ) {
return true;
}
return false;
}
});
})(jQuery);

// The registerSubmit.js submits the entered email via AJAX, returning a success or failure message, to our contactSubmit.php script, which handles the submission of the new email to a database

$(document).ready(function() {

$(“#reg-button”).click(function(){
$(“#topForm”).submit();
});

$(“#topForm”).submit(function(event) {
event.preventDefault();
var $form = $( this ),
emailAddress = $form.find( ‘input[name=”emailAddress”]’ ).val(),
token = $form.find( ‘input[name=”token”]’ ).val(),
formaction = $form.attr( ‘action’ );

if($.validation.email(emailAddress)){
$( “#reg-description” ).html (“submitting…”);
$.ajax({
type: “POST”,
url: “contactSubmit.php”,
data: “firstName=” + firstName + “&lastName=” + lastName + “&emailAddress=” + emailAddress + “&token=” + token,
success: function(){
$( “#reg-description” ).html( “Thank you. You have been registered.” );
},
});
}
else{
$( “#emailAddress” ).val (“Please enter a valid email address”);
}
});
});

// contactSubmit.php:  receive the email, check the token, clean the data, pass to a database layer API

<? php
session_start();

set_include_path(‘DBlayerClass’);
require_once(‘EmailContact.php’);

if (isset($_SESSION[‘token’]) && $_POST[‘token’] == $_SESSION[‘token’]){
if(isset($_POST[’emailAddress’])){
$emailAddress = htmlentities($_POST[’emailAddress’]);
} else { $emailAddress = ”; }

$contact = new EmailContact($emailAddress)

try {
$contact->save();
} catch (Exception $e) {
; // do something
}
//$retrieve = new EmailContact($emailAddress);
//$retrieve->load();
//print_r($retrieve);
//}
? >

Post via jQuery across domains (in this case to a Zend Controller and subsequent view) and display the results

Thursday, August 25th, 2011

the jQuery posting page, in brief:

<document…>
<head>
<script src=”http://code.jquery.com/jquery-1.5.js”></script>
</head>
<body>
<form id=”enewsform” name=”enewsform” action=”http://componentserver/controllername/post” method=”post”>
<input type=”text” name=”email” id=”email” value=”<?php echo $_REQUEST[’email’]; ?>” />
<a id=”submitsubscribe” title=”Subscribe” href=”javascript:{}” onclick=”return false;”>sign up</a>
</form>
<script src=”http://components.someserver.com/js/jquery.validation.js” type=”text/javascript”></script>
<script>
$(‘#submitsubscribe’).click(function(){
$(“#enewsform”).submit();
});

$(“#enewsform”).submit(function(event) {
event.preventDefault();
$( “#result” ).html (“submitting…”);
var $form = $( this ),
term = $form.find( ‘input[name=”email”]’ ).val(),
url = $form.attr( ‘action’ );

if($.validation.email(term)){
$.getJSON(url + “?email=” + term + “&jsoncallback=?”, function(data){
$( “#result” ).html( data[‘error’] );
if(data[‘error’]== “errormatchingstring”){
$( “#result” ).html( “Seems like it worked” );
}else{ $( “#result” ).html(data[‘error’]); }
});
}
else{ $( “#result” ).html (“Please enter your email address”); }

});
</script>

<div id=”result”></div>

// the component Zend controller in question receives the post, does whatever it does, renders its view, and we access the results from the view (don’t forget to pass data to the view with something like this:
$this-> view-> viewresult = $this-> viewData;)

<? php
echo $_REQUEST[‘jsoncallback’] . ‘(‘ . json_encode($this-> viewresult) . ‘)’;
? >

jQuery json crossdomain example

Tuesday, March 22nd, 2011

<script src=”http://code.jquery.com/jquery-1.5.js”></script>

<script>

$(“#enews_signup_form”).submit(function(event) {

// stop form from submitting normally
event.preventDefault();

$( “#result” ).html (“submitting…”);

var $form = $( this ),
term = $form.find( ‘input[name=”enews_email”]’ ).val(),
url = $form.attr( ‘action’ );

$.getJSON(url + “?email=” + term + “&jsoncallback=?”, function(data){
$( “#result” ).html( data[‘error’] );
});

});

</script>

<? php

echo $_REQUEST[‘jsoncallback’] . ‘(‘ . json_encode($this-> viewresult) . ‘)’;

?>

jQuery check if image with specific source exists on page

Thursday, November 18th, 2010

$(document).ready(function() {

$(“img”).each(function(){
imgtofind = “http://alexyz.com/images/example.jpg”;
source = $(this).attr(‘src’);
if(source == imgtofind){
alert(source); // or otherwise
}
});

}

jQuery select anchor tags that contain specific text, then change id, onClick (Capitalized!!!!), href, :contains, .attr(), .each()

Wednesday, November 17th, 2010

Easy actually, on load, select an anchor tag (or several, and do the following for .each()), that contains, among other contents, the word ‘Read’,

then set its id attribute, a Mouse event, and alter its href value:

$(document).ready(function(){

$(“a:contains(‘Read’)”).each(function(){

$(this).attr(‘id‘,’newid’);

$(this).attr(‘onClick‘, ‘return false;’); // Capitalize the C!!!!

$(this).attr(‘href‘, ‘http://www.alexyz.com’);

});

});

// alternatively, line them all up like this:

$(this).attr(‘id‘,’newid’).attr(‘onClick‘,’return false;’).attr(‘href‘,’http://www.alexyz.com’);

 

// UPDATE: Better method

$(“a[href*=‘search phrase’]”).each(function(){
var postId = $(this).attr(“href”).split(‘?’)[1].split(‘=’)[1].split(‘#’)[0]; // of course this will vary by need
$(this).attr(“href“,”?version=full&source=folder&post=”+postId);
});

Support Prototype script.aculo.us and jQuery, page built with Prototype now being pulled into page that uses jQuery

Tuesday, November 2nd, 2010

So I developed a handful of sites several years ago using Prototype and script.aculo.us,

but now they’re being pulled into/included/required by pages, a site, that is strictly jQuery,

so I need to amend the Prototype site’s functions to check which library is loaded and then act accordingly.

It begs the question, if I were doing this completely fresh, which pattern (see Design Pattern posts) would I attempt to employ…? For example, I’d love to have the option right now to simply write an adapter pattern function instead of burying this conditional within each function…

Aside from Namespacing either or both libraries of course…

Example:

<script>
accordianing = false;
function comments_cabinet()
{
if(accordianing == true)
{
setTimeout( function() { accordian(); }, 25);
}
else
{
accordianing = true;
/* scriptaculous */
if(window.Prototype)
{

if($(‘comments_button’).style.display == ‘none’) // notice the Prototype standard $(”)
{
new Effect.BlindDown(‘comments_button’, {
duration: 0.5,
afterFinish: function(){
accordianing = false;
}
});
}
else
{
new Effect.BlindUp(‘comments_button’, {
duration: 0.5,
afterFinish: function(){
accordianing = false;
}
});
}
}
else
{

$(‘#comments_button’).toggle(‘slow’); // otherwise, use the jQuery version $(‘#’)
accordianing = false;
}
return false;
}
}
</script>

Close Fancybox from within, old (1.2) and new (1.3)

Thursday, July 1st, 2010

In 1.2 this worked:

onclick=”$(“#fancy_outer”,window.parent.document).hide(); $(“#fancy_overlay”,window.parent.document).hide();

1.3+ this has changed to:

onclick=”parent.$.fancybox.close();

jQuery replace all img tags with certain source…

Monday, June 7th, 2010

$(‘img’).each(function(){
var t=$(this);
var src1 = t.attr(‘src’);
var newSrc = “images/play2.png”;
if(src1 == “images/play.png”)
{
$(this).attr(‘src’, newSrc);
}
});

jQuery .css background-image / .attr src examples

Monday, June 7th, 2010

$(“body”).css(“background-image”, “url(images/bg2.jpg)”);
$(“#header”).css(“background-image”, “url(images/bg-header2.png)”);
$(“#browse”).css(“background-image”, “url(images/bg-browse2.png)”);
$(“#paginate-slider2”).css(“background-image”, “url(images/bg-slide-thumbs2.jpg)”);
$(“#slides”).css(“background-image”, “url(images/bg-slides2.png)”);
$(“#ST-now”).css(“background-image”, “url(images/bg-STnow2.png)”);
$(“#searchBox”).attr(“src”, “images/search-box2.jpg”);
$(“#keywordsBox”).attr(“src”, “images/keywords2.jpg”);
$(“#inBox”).attr(“src”, “images/products2.jpg”);

jQuery add stylesheet dynamically

Monday, June 7th, 2010

within some logic, a function, elsewhere :

var link = $(“<link>”);
link.attr({
type: ‘text/css’,
rel: ‘stylesheet’,
href: ‘css/contentslider2.css’
});
$(“head”).append( link );

jQuery bind select change to anchor window.open variable

Thursday, April 29th, 2010

add window.open() to an anchor tag…

HTML:

select dropdown changes the source:

<div class=”name”>
<select name=”tpom” style=”float: left; width: 100px; margin-right:20px; border: 1px solid #5A3C18;” >
<option value=”downloader.php?file=folder/file.mp3″>Mp3</option>
<option value=”downloader.php?file=folder/file.zip”>Zip</option>
<option value=”downloader.php?file=folder/file.m4b”>Ipod</option>
</select>

link or button gets source from dropdown via jQuery onReady function:

$(“div.name select”).bind(“change”,function(){
$(‘#button_download’).attr(‘href’,this.value);
windowUrl = $(this).val();
//console.log(windowUrl);
});

<a onclick=”window.open(windowUrl,’download’);return false;” id=”button_download”>Download</a>

jQuery scrollTo id

Monday, April 26th, 2010

<style>

.pointer { cursor: pointer; }

</style>

<a class=”pointer” onclick=”$.scrollTo(‘#here1’, 1000); return false;”>Here</a>

<h3 id=”here1″>text</h3>

<h3 id=”here2″>text</h3>

jQuery Javascript CSS gray out faded disabled element fadeTo() onload .ready()

Friday, April 23rd, 2010

Simply fade the element you’d like faded, grayed, via your .ready onload jQuery function:

$(document).ready(function() {

jQuery(‘#top_button’).fadeTo(0, 0.5);

});

jQuery set tag element disabled

Friday, April 23rd, 2010

jQuery(‘#element1’).attr(‘disabled’,’disabled’);

jQuery setTimeout fadeOut() fadeIn() show() hide() example

Friday, April 23rd, 2010

This is a bit of craziness, still it works nicely to hide a element, show another, and then a bit later hide the latter, and again show the original.

$(‘#item1’).bind(‘click’,function() {

$(‘#item1’).fadeOut( function(){

setTimeout( function(){

$(‘#item2’).fadeIn(function() {

setTimeout( function(){

$(‘#item2’).fadeOut(function(){

setTimeout( function() {

$(‘#item1’).fadeIn();

}, 100);

});

}, 2000 );

});

}, 100);

}); return false;

});

jQuery Fancybox IE width issue don’t forget the doctype!

Wednesday, April 14th, 2010

Required, a doctype!

example:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
“http://www.w3.org/TR/html4/strict.dtd”>

also, it never hurts to go get the latest versions of jquery and fancybox, at the time of this post: http://code.jquery.com/jquery-1.4.2.min.js & fancybox-1.3.1.js worked nicely…

jQuery fancybox iframe syntax

Wednesday, April 7th, 2010

<head>

<script type=”text/javascript” src=”js/jquery.js”></script>
<script type=”text/javascript” src=”js/jquery.fancybox.1.2.1.js”></script>
<link type=”text/css” href=”css/fancybox.css” rel=”stylesheet” media=”screen” />

<script>

$(document).ready(function() {
$(“a#iframe”).fancybox({
‘speedIn’ : 600,
‘speedOut’ : 200,
‘padding’ : 20,
‘overlayOpacity’: 0.7,
‘overlayColor’ : ‘#FFF’,
‘titleShow’ : false,
});
});

</script>

</head>

<body>

<a id=”iframe” href=”The_Power_of_Meditation_Tracks.html”>View Tracks &raquo;</a><br />

</body>

jQuery change anchor tag href url via select option

Tuesday, March 30th, 2010

<select name=”tpom” onchange=”$(‘#tpom_download’).attr(‘href’,this.value);”>
<option value=”media/tpom.mp3″>MP3</option>
<option value=”media/tpom.zip”>ZIP</option>
<option value=”media/tpom.m4a”>IPOD</option>
</select>
<div style=”float:left;width:75px;margin-top:-3px;”>
<ul name=”st_btn” style=”text-align: right; float: right;”>
<li name=”submit”> <a id=”tpom_download” title=”blah” href=”media/tpom.mp3″ onclick=”return false;”>Download</a></li>
</ul>
</div>

jQuery document ready

Monday, March 8th, 2010

<html>
<head>
<script src=”jquery.1.3.2.min.js” type=”text/javascript”></script>
<script>
$(document).ready(function()
{
// display main_wrapper
$(‘.site_container’).css(‘display’, ‘block’);
});
</script>

</head>
<body>
<div id=”main_wrapper” style=”display:none;”>
Page Content
</div>
</body>
</html>