Posts

Showing posts with the label javascript

HTML Search Text and Highlight

Jumping straight to the solution: //modified search function 1. function searchtext(inputText, searchString) { 2. 3. 4. //building RegExp object for the search text g-global match,i-ignore case 5. var myregexp = new RegExp ( searchString , "gi"); 6. 7. //custom replace function just to highlight the match word in the html source 8. var myNewString = inputText . replace( myregexp, 9. function ( matchTxt,key,txt) { 10. return "<span style='background-color:red;>'" + matchTxt + "</span>"; 11. } ) ; 12. 13. //return the new highlighted text 14. return myNewString; 15. 16. } I think going through the code will be just self explanatory as the solution is straight-forward.But did you see some weird implementation ? Bingo! you found it :) It's the custom replace function. Let's get dirty with some syntax explanation and we will be soon back with the ex...

Detecting browser event closing in Javascript

I've been working on a feature where the user must be prompted to take up certain action when he leaves a page by closing the browser window or by clicking an external URL,though I searched for the best possible solution but unfortunately couldn't find one. The first thing that got my attention is the browser's "onbeforeunload" event and here is the implementation of it, window.onbeforeunload=confirmExit; function confirmExit(){ return "Do u want to close this page?" } So here the user will be prompted when he clicks the close button of the browser and when the user clicks "cancel" in prompt, it stays the same page.So far works fine. When testing is on the way , suddenly problems getting piled up and I need to reconsider the solution above, since the requirement is to "prompt the user only when he leaves the current domain (website)" and here for the above code, the user is prompted whenever...