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

Thursday, July 31, 2014

How can I check if one string contains another substring in JavaScript?

Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

Example:
var sample = "mytext";
console.log(sample.indexOf("my") > -1);
Output:
 true

Friday, June 27, 2014

Show a perticular element at top of view port using jquery


Requirement:
 Show a particular section on load of the page. only when query string present in URL
 for that page and where div id- showsection exist.


Solution:
  if(document.getElementById("showsection") != null) 
  {
    var str = document.URL.split('?')[1];
    if(str != undefined && str.length>0)
    {
      jQuery("html, body").animate({scrollTop:jQuery("#showsection").offset().top},1000);
    }
  }


In HTML page:
<div id="showsection"></div>
<div id="test">
    test document
</div>

Description:
By placing javascript code in document ready, whole page will be scrolled up and show "test".
You do not have to put anything inside "showsection" div

Thursday, May 22, 2014

Calculate distance using google api from searching zip code

I got a list if addresses showed in a list and one search filter containing textbox to insert Zip code.
Now I need to calculate the distance between the filtering Zip code and each address showing in the list. To do this I used google api.
---->
jQuery(document).ready(function () {
  if(jQuery('.atm-zip').children().val().length>0)
  {
   //get the filtering zip value and calculate the distance
    getLatLngFromAddress(jQuery('.atm-zip').children().val()); 
  }
});

var geocoder;
//filtering zip's lat
var p1lt;
//filtering zip's long
var p1ln;

function getLatLngFromAddress(postal_code) {
   if (geocoder == null) {
        geocoder = new google.maps.Geocoder();
    }
    var searchLoc;
    geocoder.geocode({ 'address': postal_code }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            searchLoc = results[0].geometry.location;
            p1lt=searchLoc.lat();
            p1ln=searchLoc.lng();

        }
          jQuery('.atm_list li').each(function(){
            //listed address's lat
            var p2lt=jQuery(this).find('.GeoLat').text();
            //listed address's long
            var p2ln=jQuery(this).find('.GeoLong').text();
           
            jQuery(this).find('.GeoDistance').text(getDistance(p2lt,p2ln) +' mi');                     
          });       
    });
}

var rad = function(x) {
  return x * Math.PI / 180;
};







//this is a function to calculate distance between 2 geographic points
function getDistance(p2lt,p2ln) {
          var R = 6378137; // Earth’s mean radius in meter
          var dLat = rad(p2lt - p1lt);
          var dLong = rad(p2ln - p1ln);
          var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
          Math.cos(rad(p1lt)) * Math.cos(rad(p2lt)) *
          Math.sin(dLong / 2) * Math.sin(dLong / 2);
          var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
          var d = R * c;
          var resultInMile=d*0.000621371;
          var finalResult=parseFloat(Math.round(resultInMile * 100) / 100).toFixed(2);
          return finalResult; // returns the distance in meter then converted to miles
      }

Wednesday, May 21, 2014

Remove Html tags from a string in Javascript

Strip html tags from a string in javascript. I needed this when I got html formatted address but for google map I required simple address text.

function strip(html)
    {
       var tmp = document.createElement("DIV");
       
        var re = new RegExp('<br>', 'g');
        html = html.replace(re, ' ');
               
        tmp.innerHTML = html;   
       
       
       return tmp.textContent || tmp.innerText || "";
    }


Pass your html string this function will trim the html tags and return it to you. If any break tag present then it will first replace that break with space then send you the text by this way you will find a clean text.

Friday, May 9, 2014

Javascript set location then hard refresh current page and set scroll position to top

I am using tabs in my page, by clicking on a link i need to open next tab in that same window, only by setting a href it is not happening. URL got changed as per #name but 2nd tab is not opening. To get rid of this problem i used following code to hard refresh the page with the new url.

<a onclick="window.scrollTo(0,0);window.location.assign('/page/subpage/#tab2');location.reload(true);" style="cursor:pointer">GO</a>

Here i am first set the current page's scroll position to top, then assign new url after that reload the page. by this way it is opening 2nd tab in the same page but it needs a refresh.

If you have any other idea please share with me.