Navigation

Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

2/17/2017

javascript search box

Mark.js is a text highlighter written in JavaScript. It can be used to dynamically mark search terms or custom regular expressions and offers you built-in options like diacritics support, separate word search, custom synonyms, iframes support, custom filters, accuracy definition, custom element, custom class name and more.

https://markjs.io/     Examples

Here is a version that will allow you to jump to matching text   

7/21/2016

IP address via javascript

Want to display different links on and off campus, using just Javascript, this uses webRTC:


function findIP(onNewIP) { //  onNewIp - your listener function for new IPs
  var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
  var pc = new myPeerConnection({iceServers: []}),
    noop = function() {},
    localIPs = {},
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
    key;

  function ipIterate(ip) {
    if (!localIPs[ip]) onNewIP(ip);
    localIPs[ip] = true;
  }
  pc.createDataChannel(""); //create a bogus data channel
  pc.createOffer(function(sdp) {
    sdp.sdp.split('\n').forEach(function(line) {
      if (line.indexOf('candidate') < 0) return;
      line.match(ipRegex).forEach(ipIterate);
    });
    pc.setLocalDescription(sdp, noop, noop);
  }, noop); // create offer and set local description
  pc.onicecandidate = function(ice) { //listen for candidate events
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
    ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
  };
}



var ul = document.createElement('ul');
ul.textContent = 'Your IPs are: '
document.body.appendChild(ul);

function addIP(ip) {
  console.log('got ip: ', ip);
  var li = document.createElement('li');
  li.textContent = ip;
  ul.appendChild(li);
}

findIP(addIP);

From http://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript-only/32841164#32841164

Using jQuery and external server

1/27/2016

Parsing string for date using Javascript


Have a CMD command that returns the user expiration date, to get it into Javascript:



var stringToParse = "You have a doctor's appointment on 2012/03/13 16:00.  Please show up on time.";
var dateString    = stringToParse.match(/\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}/);
var dt            = new Date(dateString);
console.log(dt);        //prints "Tue March 13 16:00:00 EDT 2012"



http://www.htmlgoodies.com/html5/javascript/date-parsing-using-javascript-and-regular-expressions.htm

1/26/2015

Using javascript to create Outlook email message

Want to use HTML to open Outlook with new message, use script below (only in IE):

<script type="text/javascript">
function OpenOutlookDoc(email_address,body_stuff)
{
try
{

var outlookApp = new ActiveXObject("Outlook.Application");
var nameSpace = outlookApp.getNameSpace("MAPI");
mailFolder = nameSpace.getDefaultFolder(6);
mailItem = mailFolder.Items.add('IPM.Note.FormA');
mailItem.Subject="a subject test";
mailItem.To = email_address;
mailItem.HTMLBody = body_stuff;
mailItem.display (0);
}
catch(e)
{
alert(e);
// act on any error that you get
}
}
</script>


<a href="javascript:OpenOutlookDoc('zzz@test.com','Body of message')">Click</a>


On first attempt, got error "Automation server can't create object."   Just need to do following to IE security settings: 

a) Go to Tools-->Internet Options
b) Select security tab
c) Click on Trusted Sites (or Local Intranet depending on whether your site is trusted or not)
d) Click on Custom Level
e) Ensure that "Initialize and script active x controls is not marked safe for scripting" is enabled - this comes under Activex controls and plug-ins section towards 1/4th of the scroll bar.
Click OK, OK.
Once this is completed, clear the browser cookies and cache. Close all your browser sessions. Reopen the IE to launch your site.
Try to disable the setting in step (e) to see if the problem comes back - that should give more insight to the problem.

7/24/2014

Format date with javascript

Looking to format date in standard   mm/dd/yyyy



 
var d = new Date();

var month = d.getMonth()+1;
var day = d.getDate();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();

var output = d.getFullYear() + '-' +
    ((''+month).length<2 ? '0' : '') + month + '-' +
    ((''+day).length<2 ? '0' : '') + day + ' ' +
    ((''+hour).length<2 ? '0' :'') + hour + ':' +
    ((''+minute).length<2 ? '0' :'') + minute + ':' +
    ((''+second).length<2 ? '0' :'') + second;

See this jsfiddle for a proof: http://jsfiddle.net/nCE9u/3/
You can also enclose it within function (demo is here: http://jsfiddle.net/nCE9u/4/):
 
function getISODateTime(d){
    // padding function
    var s = function(a,b){return(1e15+a+"").slice(-b)};

    // default date parameter
    if (typeof d === 'undefined'){
        d = new Date();
    };

    // return ISO datetime
    return d.getFullYear() + '-' +
        s(d.getMonth()+1,2) + '-' +
        s(d.getDate(),2) + ' ' +
        s(d.getHours(),2) + ':' +
        s(d.getMinutes(),2) + ':' +
        s(d.getSeconds(),2);
}

and use it like that:
 
getISODateTime(new Date());

or:
getISODateTime(some_other_date);

This question is a duplicate (see: How to get current date in jquery?).



http://stackoverflow.com/questions/9050763/format-date-in-jquery

6/06/2014

jQuery to detect iOS

Want to display code only for iOS devices:


function isAppleDevice(){
    return (
        (navigator.userAgent.toLowerCase().indexOf("ipad") > -1) ||
        (navigator.userAgent.toLowerCase().indexOf("iphone") > -1) ||
        (navigator.userAgent.toLowerCase().indexOf("ipod") > -1)
    );
}


From jquerybyexample.com

4/02/2014

javascript to highlight text, and to remove highlight

I had script to highlight text (using a div tag), but want to be able to quickly remove it, when I do another search, and want to highlight new phrase.




http://www.elated.com/articles/jquery-removing-replacing-moving-elements/



<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {

  // Remove the #myDiv element but leave its contents
  $('#myPara').unwrap();
}

</script>

</head>
<body>

  <div id="myDiv">
    <p id="myPara">A paragraph of text</p>
    <p>Another paragraph of text</p>
  </div>



http://www.the-art-of-web.com/javascript/search-highlight/  


Whole tag:
http://stackoverflow.com/questions/4232961/jquery-remove-a-tag-but-keep-innerhtml 






http://csdirect.iii.com/sierrahelp/Default.htm#sgcir_recent_circ_hist.html?Highlight=viewing%20the%20recent


http://csdirect.iii.com/sierrahelp/Content/Resources/Scripts/autoSearchComplete.js


function quickSearch(searchTerm) {
    if (searchTerm == "") {
        $("#autoCompleteContainer").html("");
        $("#autoCompleteContainer").append("<div id='search_suggestions_box'>Begin typing to begin your Quick Search</div>")
   
        return false;
    }
    var quickSearchArray = new Array();
    var quickSearchCount = 0;
    if (window.populatingURLS) {
        $("#search_suggestions_box").html("<span class='section_title'>Loading Data...</span>");
        return false;
    }
   

    $("#search_suggestions_box").html("<span class='section_title'>Full-Text Search</span><p id='search_text'> Continue searching for <span style='color:#B75F11'>\""+searchTerm+"\"</span> by clicking on the search icon</p><div id='suggestions_section' class='section'><span class='section_title' id='suggestions'>Documents with <span style='color:#B75F11'>\""+searchTerm+"\"</span> in the title<hr><div id='suggestions_list'><ul id='suggestions_list_ul'></ul></div></div>");
   
    myUrls = getLocalData("localStorageUrls")
    if (myUrls != undefined && (window.urls == undefined || window.urls == "" || window.urls.length <= 0)) {
        window.urls = JSON.parse(myUrls);
    }
    //Read in all of the url data
    for (x in window.urls) {
        urlData = window.urls[x];

        //IE refuses to let the below code continue. :(( Try catch is my solution for now
        try {
            t = urlData.Title;
            tLower = t.toLowerCase();
        }
        //If we fail here then just let the code fall through to return no change
        catch (e) {
            continue;
        }

        s = urlData.Source;
        //aLower = a.toLowerCase();
        searchTermLower = searchTerm.toLowerCase();
       
        searchPatt = new RegExp("("+searchTerm+")", "gi");
        if (tLower.match(searchTermLower) || s.toLowerCase().match(searchTermLower)) {
            t = t.replace(searchPatt, "<span class='mc-highlightSearch1'>$1</span>")
            //a = a.replace(searchPatt, "<span class='highlight' style='background:#ffc000'>$1</span>")
            s = s.replace(/\.\.\/Content\//g, "")+"?Highlight="+searchTerm.replace(/[^A-z0-9\.\s]/g, " ");
       
            if (window.modulesActive["highlight"]) {
                $("#suggestions_list_ul").append("<li ><A href='#"+s+"' onclick=\"$('#autoCompleteContainer').slideUp();highlightButtons('on')\">"+t+"</a></li>");
            }
            else {
            $("#suggestions_list_ul").append("<li ><A href='#"+s+"' onclick=\"$('#autoCompleteContainer').slideUp()\">"+t+"</a></li>");
            }
            quickSearchCount +=1;
            if (quickSearchCount > 20) {
                return false;
            }
        }
    }
}


10/30/2013

Using jQuery to dynamically control HTML

Have a web page with separate Windows and Apple instructions, want to only show Apple links on Apple laptop, etc.

First have link to jQuery:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>


Then you can use jQuery hide & show functions, remember to put these functions AFTER the target class or id, otherwise it will not have any effect.

<script>
$(".1class_name").hide();
$("#1id_name").show();

</script>

 You could do all P tags  ("p"), one class  (".this-class") , or one id  ("#one_id")



From w3schools.com

3/19/2013

Directions to Library - Geolocation

This uses Google Maps API to detect location of mobile device, and then show map & directions to one fixed location, like a library branch.


First add this line:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true">
</script>


Second add these functions:

<script>
 (function () {
  var directionsService = new google.maps.DirectionsService(),
   directionsDisplay = new google.maps.DirectionsRenderer(),
   createMap = function (start) {
    var travel = {
      origin : (start.coords)? new google.maps.LatLng(start.lat, start.lng) : start.address,
      destination :"38.936165,-76.996363",
      travelMode : google.maps.DirectionsTravelMode.DRIVING
      // Exchanging DRIVING to WALKING above can prove quite amusing :-)
     },
     mapOptions = {
      zoom: 10,
      // Default view: lat & lng of center of map, CUA Law School
      center : new google.maps.LatLng(38.936165,-76.996363),
      mapTypeId: google.maps.MapTypeId.ROADMAP
     };
    map = new google.maps.Map(document.getElementById("map-image"), mapOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("map-directions"));
    directionsService.route(travel, function(result, status) {
     if (status === google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(result);
     }
    });
   };
 
    // Check for geolocation support 
 
   if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
      // Success!
      createMap({
       coords : true,
       lat : position.coords.latitude,
       lng : position.coords.longitude
      });
     }, 
     function () {
      // Gelocation fallback: If can not get location
      createMap({
       coords : false,
       address : "3600 John McCormack Rd., NE Washington DC 20064"
      });
     }
    );
   }
   else {
    // No geolocation fallback: Defaults CUA LAW
    createMap({
     coords : false,
     address : "3600 John McCormack Rd., NE Washington DC 20064"
    });
   }
 })();
</script>
<div id="map-container">
<div id="map-image">&nbsp;</div>
<div id="map-directions">&nbsp;</div>
</div>


Styles to make to control look and feel:

<p><style type="text/css"> 
        #map-container {
            overflow: hidden;
        }
        #map-image {
            width: 500px;
            height: 400px;
            margin:auto;
            
            
        }
        #map-directions {
            width: 500px;
            margin:auto;
            background:#FFF;
            
        }
    </style></p>



How to do the same thing with other mapping services:

Bing  

10/22/2012

Detect mobile device via Javascript, switch to mobile page


Our CMS is looks poor on mobile drives, looked at javascript to switch to a different page on detecting mobile device:


<script type="text/javascript">
var mobile = (/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|iphone|ipod|iris|kindle|lge|maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent.toLowerCase()));
if (mobile){ document.writeln("<h2>
<a href='http://your.server.com/m.asp?insert_room=1'>Tap here for MOBILE version...</a></h2>
");
 
    }

</script>


I replaced the document switch:
document.location = 'http://your.server.com/m/'

with just adding a link to a different page:
document.writeln("<h2>
<a href='http://your.server.com/m.asp?insert_room=1'>Tap here for MOBILE version...</a></h2>

3/23/2012

Javascript Message Script by Day of Week, or Date

To display message on give date/time

<script type = "text/javascript">

var GMToffset = -5;  // Your current GMT offset, whether Standard or Daylight   style="font-size: large;"   
var now = new Date();
var dy = now.getDay(); // day of week 0-6

var themonth=now.getMonth()+1;
var thetoday=now.getDate();
var thedow = now.getDay();
var hh = now.getHours();
var theminutes = now.getMinutes();

 function GetDay(intDay){
    var DayArray = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    return DayArray[intDay];
    }

now.setHours( now.getHours() );  // GMToffset +    + now.getTimezoneOffset() / 60

var show = "No Lab Assistant on duty<br><br> " + GetDay(thedow) + "&nbsp;" + themonth + "/" + thetoday  + "&nbsp;" + hh +":"+ theminutes ;


// The GMT offset ensures that every visitor, regardless of their timezone, will see the schedule
// that is appropriate for the site owner's local time.

// Tip - for testing purposes you can put here
//dy = 3;
//hh = 7;
// or whatever to check that the right show appears at that day/time.
// days in Javascript are 0 Sunday - 6 Saturday


if (dy == 1 ) { 
if (hh >=6 && hh <9) {show = "test<br>(856) 123-4567<br>email@cua.edu   "; }
}

if (dy == 2 ) { // 2 Tuesday
if (hh >=6 && hh <9) {show = "test<br>(856) 123-4567<br>email@cua.edu      "; }
}

if (dy == 3 || dy == 4 ) { // 2 Tuesday
if (hh >=6 && hh <9) {show = "<p>test<br>123-4567<br>email@cua.edu   </p>   "; }
}




if (dy == 6) { // Saturday Note the two = signs to mean equals
if (hh >=13 && hh <18) {show = "<p>test<br>123-4567<br>email@cua.edu   </p>    "; }
} //End of Saturday Shows

if (dy == 0) { //Sunday Shows
if (hh >=13 && hh <18) {show = "<p>test<br>123-4567<br>email@cua.edu   </p> "; }
}  // End of Sunday Shows

var a = "<em>" + show + " \u00A0 \u00A0 \u00A0 \u00A0 <em> "  ;  // spaces must be separted by Unicode spaces to prevent collapse  + hh + "&nbsp;" + dy
//document.getElementById("dj").innerHTML = a;
document.write(a);
</script>

12/05/2011

IE warning message

Using Javascript to show warning only in Internet Explorer Browser:



<script language="javascript">
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}
function checkVersion()
{
  var msg = "<p>Internet Explorer Users:<br> You will get a popup warning message (view content that was delivered securely).  You can <a href='http://blogs.msdn.com/b/askie/archive/2009/05/14/mixed-content-and-internet-explorer-8-0.aspx' target='_blank'>change IE settings</a> to avoid this warning, or use Firefox or Chrome instead.</p><p>&nbsp;</p>";
  var ver = getInternetExplorerVersion();

  if ( ver > -1 )
  {
    if ( ver >= 8.0 )
     
  document.write( msg );
  }

}

checkVersion();       


function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function checkVersion()
{
var msg = "
Internet Explorer Users: You will get a popup warning message (view content that was delivered securely).  You can change IE settings to avoid this warning, or use Firefox or Chrome instead.

";
var ver = getInternetExplorerVersion();

if ( ver > -1 )
{
if ( ver >= 8.0 )

document.write( msg );
}

}

checkVersion();       

</script>

3/23/2011

How to embed Javascript on TWEN pages?

We recently subscribed to OCLC's QuestionPoint, and the service comes with a Qwidget feature (a chat widget) they we wanted to place on web pages & all the course TWEN pages in Westlaw.

Qwidget requires JavaScript, and at first glance, TWEN would not allow it, it just stripped it away.

But then I tried an IFRAME pointing to a page that just had the Qwidget, and TWEN was fine with it:

<iframe scrolling="auto" height="300" frameborder="0" width="200" src="http://lib.law.cua.edu/home/pages/qwidget1.html">

Make the frame a bit larger, so no scroll bars on horizonal or vertical.

Code box is from Tutzone 
TWEN is course management system from Westlaw

1/13/2011

How to embed Blog posts into web pages?


Using  gfeedfetcher.js  from dynamic drive.  This takes RSS feed from a blog, and allows you to embed the content into a web page.


<script src="http://www.google.com/jsapi?key=Your-API-key" type="text/javascript">
</script>
<script src="http://your-server.com/gfeedfetcher.js" type="text/javascript">
</script>

<script type="text/javascript">
var cssfeed=new gfeedfetcher("example2", "test2class", "")
cssfeed.addFeed("CSS Drive", "URL of your ") //Specify "label" plus URL to RSS feed
cssfeed.displayoptions("description") //show the specified additional fields
cssfeed.setentrycontainer("p") //Display each entry as a list (li element)
cssfeed.filterfeed(5, "date") //Show 10 entries, sort by date
cssfeed.init() //Always call this last
</script>