Hide Javascript on site - javascript

On my website I have Javascript that replaces the standard menu if it's viewed on a phone. If I remove the Javascript, the desktop menu will be shown. The code for the script is shown below and the attached image show the javascript menu show from a phone view:
What I want is the Javascript itself to be executed because then the desktop menu wont be shown, but I want the "Please choose page" and the list / box itself to be hidden like it's never even been there.
Can this be done somehow? Users should only se a white space where instead of the box shown in the image.
jQuery.noConflict()(function($) {
$("<select />").appendTo("nav");
$("<option />", {
"selected": "selected",
"value": "",
"text": "Please choose page"
}).appendTo("nav select");
$("nav a").each(function() {
var el = $(this);
var perfix = '';
switch (el.parents().length) {
case (11):
perfix = '';
break;
case (13):
perfix = '-- ';
break;
default:
perfix = '';
break;
}
$("<option />", {
"value": el.attr("href"),
"text": perfix + el.text()
}).appendTo("nav select");
$("nav select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
});
function bookmarksite(title, url) {
if (window.sidebar)
window.sidebar.addPanel(title, url, "");
else if (window.opera && window.print) {
var elem = document.createElement('a');
elem.setAttribute('href', url);
elem.setAttribute('title', title);
elem.setAttribute('rel', 'sidebar');
elem.click();
} else if (document.all)
window.external.AddFavorite(url, title);
}

you could use cordova https://cordova.apache.org/
this would allow you to understand if you are on a mobile device or instead in a computer web brownser with just a:
if(typeof cordova == 'undefined' || !cordova) {
//Web browser JS
} else {
//Mobile phone JS
}
this way you can just do a addAttr.("hidden", true) to hide in the mobile part or split your code in a cleaner way.
Hope this is helpful

Related

.on("DOMNodeInserted", function(e){, e.currentTarget is always #document

I'm in the process of updating a 2-year old application and part of that application has the following:
function setupListener(currentXmlHttpRequests){
debugger;
$(document).unbind("DOMNodeInserted");
$(document).bind("DOMNodeInserted", function(e){
debugger;
console.log(e.currentTarget.id);
if(e.target.id=="page-bottom"){
refreshFilterList("Last 6 Months Of Launches");
refreshQuickJump(filtered);
$("#mySelect").on('change', function() {
var val = this.value;
if(val == "")
return;
document.getElementById(val).scrollIntoView();
var element = document.getElementById('mySelect');
element.value = "";
});
$("#datacenter").SumoSelect({placeholder: "All Datacenters"});
$("#year").SumoSelect({placeholder: "All Years"});
$("#platform").SumoSelect({placeholder: "All Platforms"});
$("#tech").SumoSelect({placeholder: "No Technologies"});
$("#tech")[0].sumo.selectItem(1);
$("#tech")[0].sumo.selectItem(2);
$("#tech")[0].sumo.selectItem(3);
$("#version").SumoSelect({placeholder: "All Versions"});
$("#query").keyup(function(e) {
if(e.keyCode == 13) {
setFilters();
changeURL(scriptName);
if(checkFiltersDefault())
loadDefault();
else
filter(filteredServiceNames[env], true);
refresh(currentXmlHttpRequests);
}
});
$("#search").on("click", function(){
setFilters();
changeURL(scriptName);
if(checkFiltersDefault())
loadDefault();
else
filter(filteredServiceNames[env], true);
refresh(currentXmlHttpRequests);
});
$("#clear").on("click", function(){
clearFilters();
changeURL(scriptName);
loadDefault();
refresh(currentXmlHttpRequests);
});
}
});
}
But when this is entered, e.currentTarget is always #document and e.target.id is always blank. This results in the listeners never being applied.
page-bottom is setup in another method before this one:
function setupLast(dashboard) {
dashboard.rows.push({
title: 'Chart',
height: 25,
editable: false,
panels: [{
title: ' ',
type: 'text',
span: 0,
mode: 'html',
content: "<!DOCTYPE html><html><body><div id=\"page-bottom\" style=clear:both></div></body></html>",
height: 25,
transparent: true,
id: -1
}]
});
}
The guy who wrote this originally inserted this div as a way for us to watch for when the page has finished loading. His old docs have:
Most dashboards have an invisible panel that is added at the end of
the dashboard for the purpose of knowing when it is safe to perform
jquery event binding, among other things. This works by using jquery's
'DOMNodeInsert' event to wait for the div inside the panel to be added
to the page.
I'm not exactly sure what the issue is - if maybe when the base application was upgraded (2 years worth of upgrades) it upgraded the jquery version, or if I'm just missing something. I can see that page-bottom does actually end up in the page. When the page loads though, these listener setups never get executed.
I would just do away with that div detection mechanism and use the jQuery api method:
$(document).ready(function() {
refreshFilterList("Last 6 Months Of Launches");
refreshQuickJump(filtered);
$("#mySelect").on('change', function() {
var val = this.value;
if(val == "")
return;
document.getElementById(val).scrollIntoView();
var element = document.getElementById('mySelect');
element.value = "";
});
$("#datacenter").SumoSelect({placeholder: "All Datacenters"});
$("#year").SumoSelect({placeholder: "All Years"});
$("#platform").SumoSelect({placeholder: "All Platforms"});
$("#tech").SumoSelect({placeholder: "No Technologies"});
$("#tech")[0].sumo.selectItem(1);
$("#tech")[0].sumo.selectItem(2);
$("#tech")[0].sumo.selectItem(3);
$("#version").SumoSelect({placeholder: "All Versions"});
$("#query").keyup(function(e) {
if(e.keyCode == 13) {
setFilters();
changeURL(scriptName);
if(checkFiltersDefault())
loadDefault();
else
filter(filteredServiceNames[env], true);
refresh(currentXmlHttpRequests);
}
});
$("#search").on("click", function(){
setFilters();
changeURL(scriptName);
if(checkFiltersDefault())
loadDefault();
else
filter(filteredServiceNames[env], true);
refresh(currentXmlHttpRequests);
});
$("#clear").on("click", function(){
clearFilters();
changeURL(scriptName);
loadDefault();
refresh(currentXmlHttpRequests);
});
});
Try using e.target instead of currentTarget

Outbound link tracking and 'undefined' links

I've installed the following outbound link tracking code on a website which is working well.
The trouble is it's causing an issue with the dots in an image slider also on the site (using flexslider). When these dots are clicked, they normally move the image slider to that slide, but the link tracking script is causing the page to reload and go to '/undefined' (i.e. www.domain.com/undefined).
$(function() {
$("a").on('click',function(e) {
var url = $(this).attr("href");
if (e.currentTarget.host != window.location.host) {
_gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host.replace(':80',''), url, 0);
if (e.metaKey || e.ctrlKey || this.target == "_blank") {
var newtab = true;
}
if (!newtab) {
e.preventDefault();
setTimeout('document.location = "' + url + '"', 100);
}
}
});
});
Any tips on how to solve this would be massively appreciated.
Thanks in advance,
Tom
You could filter your selector results or check when href is undefined, which seems to be the case for the dots of the slider, like this:
$(function() {
$("a").on('click', function(e) {
var url = $(this).attr("href");
if (url && e.currentTarget.host != window.location.host) {
_gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host.replace(':80', ''), url, 0);
if (e.metaKey || e.ctrlKey || this.target == "_blank") {
var newtab = true;
}
if (!newtab) {
e.preventDefault();
setTimeout('document.location = "' + url + '"', 100);
}
}
});
});

Select different word each time TAB key is pressed

Move across each word in a sentences.
I have created shortcut key for enter in my application as, it will move towards and focus each input control in my page.
I need to set keyboard shortcuts for tab as, it has to select each string of a sentences which are in some textbox. For example txtAddress contain value like "Hi i am new user", if I press tab key it has to select a string "hi" then "i" then "am" then "new" then "user" after that it has to focus a next input control.
I have tried with following JS to focus next input control but don't know how to select each word in textbox.
$(document).unbind('keydown');
$(document).bind('keydown', 'tab', function assets() {
try {
var inputs = $(":input:not(input[type='hidden'])");
var CurInput = inputs.get(inputs.index(document.activeElement));
var nextInput = inputs.get(inputs.index(document.activeElement) + 1);
if (CurInput && nextInput.type == "text" && CurInput.style.display != "none") {
var strval = CurInput.value;
if (!strval) {
if (nextInput && nextInput.type != "hidden" && nextInput.style.display != "none") {
nextInput.focus();
}
}
}
else if (nextInput && nextInput.type != "hidden" && nextInput.style.display != "none") {
nextInput.focus();
}
return false;
}
catch (e) {
}
});
http://jsbin.com/cihahigevo/1/edit?html,js,output
var textarea = $('textarea')[0],
index = 0;
$(document).on('keydown.tab', function(e){
if( e.keyCode == 9 ){
textarea.focus();
textarea.value = textarea.value.trim() + ' ';
index = textarea.value.indexOf(' ', index) + 1;
textarea.setSelectionRange(0, index);
}
return false;
});
It's never a good idea to override a users keyboard, especially the tab button.
The tab button is used by people who (for whatever reason) don't use a mouse to navigate sites by 'tabbing' between buttons, form fields, etc.
If you remove this functionality by overriding the tab key, you've suddenly made your site unaccessible to these users.
You may also run afoul of you countries laws on website accessibility (the Disability & Discrimation act in the UK).

How to remove text selection from selected text which is coming by default on page load?

When we refresh or reload the page, you can see a selected text in middle of circle when you click on below image portion:
Discuss Goals & Concern
Cash Flow Analysis
Tax Analysis...
And so on.
Example: http://ivyfa.advisorproducts.com/financial-planning-process
The selected text is only coming on the first click - when you click again on those image portions you will not see selected text. So I want to remove the selection from the text on the first attempt too.
It's difficult for me to explain this issue. Below is the JS code I am using - I think the issue is in the ChangeText() functionality.
/*----------Text change on click - Our Process page---------------*/
var prev;
var IdAry = ['slide1', 'slide2', 'slide3', 'slide5', 'slide8', 'slide9', 'slide12', 'slide13', 'slide14', 'slide15', 'slide16'];
window.onload = function() {
for (var zxc0 = 0; zxc0 < IdAry.length; zxc0++) {
var el = document.getElementById(IdAry[zxc0]);
if (el) {
setUpHandler(el);
el.onmouseover = function() {
$(this).addClass("hover");
}
el.onmouseout = function() {
$(this).removeClass("hover");
}
}
}
}
function setUpHandler(el) {
/*---------This is used to add selected class on clicked id only and remove class selected from rest---------*/
$("#" + IdAry.join(",#")).click(function() {
$(this).addClass("selected");
$("#graphics .selected").not(this).removeClass("selected");
})
/*---------This will add show hide class to thier spans and vise versa-------*/
$("#" + IdAry.join(",#")).click(
function() {
changeText(this, "hide", "show");
},
function() {
changeText(this, "show", "hide");
})
}
function changeText(obj, cl1, cl2) {
obj.getElementsByTagName('SPAN')[0].className = "hide";
obj.getElementsByTagName('SPAN')[1].className = "show";
if (prev && obj !== prev) {
prev.getElementsByTagName('SPAN')[0].className = "show";
prev.getElementsByTagName('SPAN')[1].className = "hide";
}
prev = obj
}
I only want to remove the selected text from the text in the middle when you click on different-2 image tag.
Image to view selected text:
You should clear text selection once you display your control; you can do this by calling this function (should be fully cross-browser):
function clearSelection() {
if (window.getSelection) window.getSelection().removeAllRanges();
else if (document.selection) document.selection.empty();
}

Bug w IE8 Using Javascript to Insert Text at Caret

Focusing on IE, I have a textbox (single line <input/>) for which I need to insert text where the caret/cursor is. The text within a div is inserted at the caret position when the div is double clicked.
Bug: Text is inserted into the textbox, but at the beginning of the string in the textbox and not where the caret position is.
The following code works fine using the multiline input (no bug), the bug only occurs with the single line input.
Here is the simple Javascript for IE (other browser support has been removed for simplicity):
$.fn.insertAtCaret = function (tagName) {
return this.each(function () {
if (this.selectionStart || this.selectionStart == '0') {
//MOZILLA support
} else if (document.selection) {
//IE support
this.focus();
sel = document.selection.createRange();
sel.text = tagName;
} else {
//ELSE
}
});
};
Just so you have everything in front of you, here is the JQuery that calls $.fn.insertAtCaret:
$("#Subject").mousedown(function () { $("#InsertAtCaretFor").val("Subject"); });
$("#Subject").bind('click, focus, keyup', function () { $("#InsertAtCaretFor").val("Subject"); });
$("#Comment").mousedown(function () { $("#InsertAtCaretFor").val("Comment"); });
$("#Comment").bind('click, focus, keyup', function () { $("#InsertAtCaretFor").val("Comment"); });
$(".tag").dblclick(function () {
if ($("#InsertAtCaretFor").val() == "Comment") $("#Comment").insertAtCaret($(this).text());
if ($("#InsertAtCaretFor").val() == "Subject") $("#Subject").insertAtCaret($(this).text());
});
As you can see, when one of the two <input/>s are clicked, focused, etc., a hidden field (ID="InsertAtCaretFor") value is set to either "Subject" or "Comment". When the tag is double-clicked, its .text() is inserted at the caret position within the <input/> specified by the hidden field's value.
Here are the fields:
<%=Html.Hidden("InsertAtCaretFor") %>
<div class="form_row">
<label for="Subject" class="forField">
Subject:</label>
<%= Html.TextBox("Subject", "", new Dictionary<string, object> { { "class", "required no-auto-validation" }, { "style", "width:170px;" }, { "maxlength", "200" } })%>
</div>
<div class="form_row">
<label for="Comment" class="forField">
Comment:</label>
<%= Html.TextArea("Comment", new Dictionary<string,object> { {"rows","10"}, {"cols","50"}, { "class", "required"} })%>
</div>
Finally, here is an image so you can visually understand what I'm doing:
http://www.danielmckenzie.net/ie8bug.png
I'm using a different insertAtCaret code I found from googling around. Works on single inputs and textareas just fine.
$.fn.extend({
insertAtCaret: function (myValue) {
var $input;
if (typeof this[0].name != 'undefined')
$input = this[0];
else
$input = this;
if ($.browser.msie) {
$input.focus();
sel = document.selection.createRange();
sel.text = myValue;
$input.focus();
}
else if ($.browser.mozilla || $.browser.webkit) {
var startPos = $input.selectionStart;
var endPos = $input.selectionEnd;
var scrollTop = $input.scrollTop;
$input.value = $input.value.substring(0, startPos) + myValue + $input.value.substring(endPos, $input.value.length);
$input.focus();
$input.selectionStart = startPos + myValue.length;
$input.selectionEnd = startPos + myValue.length;
$input.scrollTop = scrollTop;
} else {
$input.value += myValue;
$input.focus();
}
}
});
After looking at your js code I'd change:
$(".tag").dblclick(function () {
if ($("#InsertAtCaretFor").val() == "Comment") $("#Comment").insertAtCaret($(this).text());
if ($("#InsertAtCaretFor").val() == "Subject") $("#Subject").insertAtCaret($(this).text());
});
To the following:
$(".tag").dblclick(function () {
if ($("#InsertAtCaretFor").val() == "Comment") {
$("#Comment").insertAtCaret($(this).text());
}
if ($("#InsertAtCaretFor").val() == "Subject") {
$("#Subject").insertAtCaret($(this).text());
}
});
Those two inline if statements with no ending curly brace look dangerous!
I've come the same problem myself in IE8. It seems that for INPUT type="text", it does not fill in selectionStart and selectionEnd. IE9 does, however.

Categories