When I create an input box in topbar using bootstrap css, the placeholder value is visible in all browsers except IE. But in twitter site they're making it visible somehow(not javascript, cause I turned off scripts and tested). Can anyone out there help me ?
I was having similar issues and faked the same placeholder functionality for IE by doing this.
<script type="text/javascript">
$(function() {
if(!$.support.placeholder) {
var active = document.activeElement;
$(':text').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text').blur();
$(active).focus();
$('form').submit(function () {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});
</script>
Source: http://www.cssnewbie.com/cross-browser-support-for-html5-placeholder-text-in-forms/
Would be good to see your code, but I'll assume you set the placeholder="my placeholder" attribute on the input tag. This is new HTML5 functionality, so that's why it is working without JavaScript.
There's a few reasons I can think of why it's not working.
Set your doctype correctly to html, which indicates html5.
Make sure there's nothing before the doctype declaration, not even empty lines.
Set your css-styles correctly. You'll have to use vendor prefixed
since it's a relatively new feature:
::-webkit-input-placeholder { color:#999; };
:-moz-placeholder { color:#999; };
:-ms-input-placeholder { color:#999; };
:placeholder { color:#999; };
.placeholder { color:#999; };
Related
I am working with AngularJS (pretty new). I have encountered a challenge which is if the textarea value is to big I have to make it scrollable as well as the border around it and if not I have to remove the border and scrolling as well. I try adding the directive but couldn't make it work.
Let me know if there is any work around it. I appreciate your time and help.
Updated:
angular.module('myApp')
.directive('removeBorder', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
if (element[0].clientHeight < element[0].scrollHeight) {
console.log(element.clientHeight);
console.log(element.scrollHeight);
console.log('ELEMENT: ' + element[0]);
angular.element(element[0]).removeClass('scroll');
}
}
};
});
I made you an example with nativeJS and angularJS with native JS. Just check Elements clientHeight and scrollHeightattribute to make it work.
angularJS directive
angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope) {}])
.directive('removeBorder', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
if (element[0].clientHeight >= element[0].scrollHeight) {
console.log(element[0].clientHeight);
console.log(element[0].scrollHeight);
angular.element(element[0]).addClass('no-scroll');
}
}};
});
Native JS - Plunker
function hasScrollbar(elemId) {
elem = document.getElementById(elemId);
if (elem.clientHeight < elem.scrollHeight) {
alert("The element #" + elemId + " has a vertical scrollbar!");
} else {
alert("The element #" + elemId + " doesn't have a vertical scrollbar.");
elem.style.border= "0";
}
}
Scrollable shoulb be set automatically. Or use css:
textarea { overflow-y:scroll; }
Google adds styles to the maps container that override my styles.
I know how to fix this. But the API (v3.8/9/exp) also loads the webfont "Roboto" which I don't really need/want.
Is there any setting/option/way around this?
Can I prevent the API from adding the extra CSS?
This is the code the google-maps-API adds to the <head> of my page:
<style type="text/css">
.gm-style .gm-style-cc span,
.gm-style .gm-style-cc a,
.gm-style .gm-style-mtc div {
font-size:10px
}
</style>
<link type="text/css"
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700">
<style type="text/css">
#media print {
.gm-style .gmnoprint,
.gmnoprint {
display:none
}
}
#media screen {
.gm-style .gmnoscreen,
.gmnoscreen {
display:none
}
}
</style>
<style type="text/css">
.gm-style {
font-family: Roboto,Arial,sans-serif;
font-size: 11px;
font-weight: 400;
text-decoration: none
}
</style>
You can replace the insertBefore method before the Google script invokes it:
http://jsfiddle.net/coma/7st6d9p2/
var head = document.getElementsByTagName('head')[0];
// Save the original method
var insertBefore = head.insertBefore;
// Replace it!
head.insertBefore = function (newElement, referenceElement) {
if (newElement.href && newElement.href.indexOf('//fonts.googleapis.com/css?family=Roboto') > -1) {
console.info('Prevented Roboto from loading!');
return;
}
insertBefore.call(head, newElement, referenceElement);
};
// Check it!
new google.maps.Map(document.getElementById('map'), {
center : new google.maps.LatLng(51.508742,-0.120850),
zoom : 16,
mapTypeId : google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
zoomControl : false,
panControl : false,
mapTypeControl : false
});
UPDATE 10/2017
Google changed the approach of how they inject the styles on the page. Currently they inserting an empty style element and then changing the contents of this style element with Robot font. Here is a new solution:
// Preventing the Google Maps libary from downloading an extra font
(function() {
var isRobotoStyle = function (element) {
// roboto font download
if (element.href
&& element.href.indexOf('https://fonts.googleapis.com/css?family=Roboto') === 0) {
return true;
}
// roboto style elements
if (element.tagName.toLowerCase() === 'style'
&& element.styleSheet
&& element.styleSheet.cssText
&& element.styleSheet.cssText.replace('\r\n', '').indexOf('.gm-style') === 0) {
element.styleSheet.cssText = '';
return true;
}
// roboto style elements for other browsers
if (element.tagName.toLowerCase() === 'style'
&& element.innerHTML
&& element.innerHTML.replace('\r\n', '').indexOf('.gm-style') === 0) {
element.innerHTML = '';
return true;
}
// when google tries to add empty style
if (element.tagName.toLowerCase() === 'style'
&& !element.styleSheet && !element.innerHTML) {
return true;
}
return false;
}
// we override these methods only for one particular head element
// default methods for other elements are not affected
var head = $('head')[0];
var insertBefore = head.insertBefore;
head.insertBefore = function (newElement, referenceElement) {
if (!isRobotoStyle(newElement)) {
insertBefore.call(head, newElement, referenceElement);
}
};
var appendChild = head.appendChild;
head.appendChild = function (textNode) {
if (!isRobotoStyle($(textNode)[0])) {
appendChild.call(head, textNode);
}
};
})();
ORIGINAL ANSWER
Thanks to coma for the solution! I also decided to intercept styles which override the font-family, font-size and font-weight. The complete solution for modern browsers and IE8+:
// Preventing the Google Maps libary from downloading an extra font
var head = $('head')[0];
var insertBefore = head.insertBefore;
head.insertBefore = function (newElement, referenceElement) {
// intercept font download
if (newElement.href
&& newElement.href.indexOf('https://fonts.googleapis.com/css?family=Roboto') === 0) {
return;
}
// intercept style elements for IEs
if (newElement.tagName.toLowerCase() === 'style'
&& newElement.styleSheet
&& newElement.styleSheet.cssText
&& newElement.styleSheet.cssText.replace('\r\n', '').indexOf('.gm-style') === 0) {
return;
}
// intercept style elements for other browsers
if (newElement.tagName.toLowerCase() === 'style'
&& newElement.innerHTML
&& newElement.innerHTML.replace('\r\n', '').indexOf('.gm-style') === 0) {
return;
}
insertBefore.call(head, newElement, referenceElement);
};
I found above solution to prevent websites with Google Maps from loading Roboto.
If you - like I do - use Wordpress, there might be other plugins referring to Google Fonts.
However, I struggled on some of my websites with the above code, since parts of it (1) affected also other styles to load, (2) "killed" styles, which intentionally not only contained gm-style, but other styles as well and (3) not affected other Google Fonts to load, where one or another plugin added links to fonts.googleapis.com by DOM-manipulation as well.
The below worked for me. It simply prevents other scripts from adding any tag having https://fonts.googleapis.com in it's href-attribute.
(function($) {
var isGoogleFont = function (element) {
// google font download
if (element.href
&& element.href.indexOf('https://fonts.googleapis.com') === 0) {
return true;
}
return false;
}
// we override these methods only for one particular head element
// default methods for other elements are not affected
var head = $('head')[0];
var insertBefore = head.insertBefore;
head.insertBefore = function (newElement, referenceElement) {
if (!isGoogleFont(newElement)) {
insertBefore.call(head, newElement, referenceElement);
}
};
var appendChild = head.appendChild;
head.appendChild = function (textNode) {
if (!isGoogleFont($(textNode)[0])) {
appendChild.call(head, textNode);
}
};
})(jQuery);
Unfortunately, I'm a newb and I couldn't get the other suggestions to work. So I removed all the Google fonts from the DOM. I hope it helps.
const googleFont = document.querySelector('link[rel="stylesheet"][href*="fonts.googleapis.com"]');
if (googleFont) {
googleFont.remove();
}
For TypeScript a solution would be:
const head = document.head;
const insertBefore = head.insertBefore;
head.insertBefore = <T extends Node>(
newElement: T,
referenceElement: Node
): T => {
if (
newElement instanceof Element &&
newElement?.hasAttribute('href') &&
newElement?.getAttribute('href')?.includes('fonts.googleapis')
) {
return newElement;
}
insertBefore.call(head, newElement, referenceElement);
return newElement;
};
Is there a TamperMonkey equivalent to GreaseMonkey's GM_addStyle method for adding CSS?
In GreaseMonkey, you can add a bunch of CSS properties to multiple elements like so:
GM_addStyle("body { color: white; background-color: black; } img { border: 0; }");
To do the equivalent in TamperMonkey, I'm currently having to do the following:
function addGlobalStyle(css) {
var head, style;
head = document.getElementsByTagName('head')[0];
if (!head) { return; }
style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = css;
head.appendChild(style);
}
addGlobalStyle('body { color: white; background-color: black; }');
This works, but is there a built-in GM_addStyle equivalent for TamperMonkey that saves me from having to repeat this on every script?
Version 4.0 or +, update of 2018
ReferenceError: GM_addStyle is not defined
You need to create your own GM_addStyle function, like this :
// ==UserScript==
// #name Example
// #description Usercript with GM_addStyle method.
// ==/UserScript==
function GM_addStyle(css) {
const style = document.getElementById("GM_addStyleBy8626") || (function() {
const style = document.createElement('style');
style.type = 'text/css';
style.id = "GM_addStyleBy8626";
document.head.appendChild(style);
return style;
})();
const sheet = style.sheet;
sheet.insertRule(css, (sheet.rules || sheet.cssRules || []).length);
}
//demo :
GM_addStyle("p { color:red; }");
GM_addStyle("p { text-decoration:underline; }");
document.body.innerHTML = "<p>I used GM_addStyle.</p><pre></pre>";
const sheet = document.getElementById("GM_addStyleBy8626").sheet,
rules = (sheet.rules || sheet.cssRules);
for (let i=0; i<rules.length; i++)
document.querySelector("pre").innerHTML += rules[i].cssText + "\n";
DEPRECATED
If GM_addStyle(...) doesn't work, check if you have #grant GM_addStyle header.
Like this :
// ==UserScript==
// #name Example
// #description See usercript with grant header.
// #grant GM_addStyle
// ==/UserScript==
GM_addStyle("body { color: white; background-color: black; } img { border: 0; }");
According to the TamperMonkey documentation, it supports GM_addStyle directly, like GreaseMonkey does. Check your include/match rules are correct, then add this demo code to the top of your userscript:
GM_addStyle('* { font-size: 99px !important; }');
console.log('ran');
I just tested it on a fresh userscript in Chrome 35 and it worked as expected. If you have any other #grant rule, you will need to add one for this function, otherwise it should be detected and granted automatically.
If somebody is interessted, I changed the code so you don't have to write "!important" after every css rule. Of course this only works, if you use the function instead of GM_addStyle.
function addGlobalStyle(css) {
var head, style;
head = document.getElementsByTagName('head')[0];
if (!head) { return; }
style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = css.replace(/;/g, ' !important;');
head.appendChild(style);
}
The output of this "addGlobalStyle('body { color: white; background-color: black; }');",
will be "body { color: white !important; background-color: black !important; }');"
I was having this same issue. I tried all the fixes, making sure to have // #grant GM_addStyle in the header. My issue was, I also had the default code's // #grant none at the bottom of the header. Removed that piece and now all my css works. Hope this helps someone else if they are stuck on this too.
I have GreaseMonkey scripts that run in various engines, this covers all varieties:
--snip--
// #include *.someplace.com/*
// #grant GM_addStyle
// ==/UserScript==
(function() {
'use strict';
let myCSS=(<><![CDATA[
body { background: #121212 url(https://somewhere.github.io/boss/imgs/bg.jpg) top left repeat !important; }
]]></>).toString();
// workaround for various GreaseMonkey engines
if (typeof GM_addStyle != "undefined") {
GM_addStyle(myCSS);
} else if (typeof PRO_addStyle != "undefined") {
PRO_addStyle(myCSS);
} else if (typeof addStyle != "undefined") {
addStyle(myCSS);
} else {
var node = document.createElement("style");
node.type = "text/css";
node.appendChild(document.createTextNode(myCSS));
var heads = document.getElementsByTagName("head");
if (heads.length > 0) {
heads[0].appendChild(node);
} else {
// no head yet, stick it whereever
document.documentElement.appendChild(node);
}
}
This excerpt from a script that was written in 2018 that is known to work in GreasMonkey, TamperMonkey, and ViolentMonkey (probably others too). Adapt the above mentioned addGlobalStyle(css) functions and you should be good to go anywhere .
My 2 cents on the topic, thought it might be interesting to someone, I modified PaarCrafter's answer, to allow multiple lines without brackets:
usage:
addGlobalStyle`
button.special {
position: relative;
top: -3em;
}
`
// string templating ('Template literals') works anyways
addGlobalStyle(`p {
color: red;
}`)
// Still works
addGlobalStyle('p {color: red;}')
Modified version:
function addGlobalStyle(css = '') {
let target = documnet.head || document.body;
let style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = (css || arguments.length ? arguments[0][0] : '').replaceAll(';', ' !important;');
target.append(style);
}
Here is the solution used by https://userstyles.org, for example when you click on the link "Install style as userscript" on a style page like https://userstyles.org/styles/23516/midnight-surfing-global-dark-style:
if (typeof GM_addStyle != "undefined") {
GM_addStyle(css);
} else if (typeof PRO_addStyle != "undefined") {
PRO_addStyle(css);
} else if (typeof addStyle != "undefined") {
addStyle(css);
} else {
var node = document.createElement("style");
node.type = "text/css";
node.appendChild(document.createTextNode(css));
var heads = document.getElementsByTagName("head");
if (heads.length > 0) {
heads[0].appendChild(node);
} else {
// no head yet, stick it whereever
document.documentElement.appendChild(node);
}
}
Note: the code will work on Greasemonkey 4 as well as similar addons. I don't use Tampermonkey which is not open source but this answer may help other users finding this question. It will try to use several built-in functions of different addons before using a pure JavaScript solution. You may only need the code from the else block.
The "if" condition checking the head tag length may not be needed if you are sure the page has a head tag and you can add the node to the head like this instead : document.head.appendChild(node);. However I noticed sometimes there is a JavaScript error saying the head is undefined or null depending on the method used, for example on facebook.com while logged out (at least when using // #run-at document-start which is required for a dark theme to avoid flickering). So checking the length can be useful in this case.
If you want to use multiple lines of CSS code, you can create the css variable with backticks like this:
var css = `
CODE HERE
`;
Update: I just saw this solution is also used in another answer but there was no source mentioned. However you may see the console error document.documentElement is null but it can be solved with a MutationObserver workaround: https://github.com/greasemonkey/greasemonkey/issues/2996#issuecomment-906608348.
Need help..Unable to iterate thru auto suggestions using up and down arrow keys on keyboard here is little code snippet
dojo.require("dojo.NodeList-manipulate");
dojo.require("dojo.NodeList-traverse");
dojo.ready(function () {
var div = dojo.query("#list-of-items");
console.log(dojo.byId("search").getBoundingClientRect());
dojo.connect(dojo.byId("search"), "onkeyup", function (evt) {
if (dojo.byId("search").value.trim() === "") {
dojo.forEach(div.query("li"), function (elm, i) {
dojo.style(elm, {
"display": "block"
});
});
dojo.style(dojo.query("#list-of-items")[0], {
"display": "none"
});
if(evt.keyCode == 40){
return;
}else if(evt.keyCode == 38){
return;
}
} else {
dojo.style(dojo.query("#list-of-items")[0], {
"display": "inline-block"
});
}
searchTable(this.value, evt);
});
function searchTable(inputVal, e) {
console.log(inputVal);
var list = dojo.query('#list-of-items');
dojo.forEach(list.query('li'), function (elm, i) {
var found = false;
var regExp = new RegExp(inputVal, 'i');
if (regExp.test(elm.innerText)) {
found = true;
if(i===0){
dojo.attr(elm, { className: "hlight" });
}
dojo.style(elm, {
"display": "block"
});
return false;
}
if (found == true) {
dojo.style(elm, {
"display": "block"
});
} else {
dojo.style(elm, {
"display": "none"
});
}
});
}
});
and also highlight auto suggest using this css class
.hlight{
background:#faae00;
font-weight:bold;
color:#fff;
}
Please see working Fiddle here
Thanks
The best thing to do is to keep an index that contains the highlighted value, then increment/decrease that index every time the up/down arrow is pressed.
You will also have to send that index with your searchTable() function so that it can add the .hlight class to the correct elements.
The hardest part is to correct that index when someone uses the up arrow when you're already on the first element (or the down arrow when you're on the last arrow). I solved that by adding a class .visible to the elements that are visible (in stead of just adding display: block or display: none), this way you can easily query all items that are visible.
I rewrote your code a bit, ending up with this. But still, my original question is still left, why don't you use the dijit/form/ComboBox or dijit/form/FilteringSelect? Dojo already has widgets that do this for you, you don't have to reinvent the wheel here (because it probably won't be as good).
I have made an custom collapsible fieldset control in asp.net. I use jquery to add the toggle effects. The control works perfectly but when i am using my fieldsets inside an updatepanel, afer a postback i loose my jquery logic because of the document.ready.
Now i have read about the new Live() function of Jquery but i don't get it working. What do i do wrong? Has someone the answer??
Thanks a lot
My Jquery code is:
$(document).ready(function() {
$.fn.collapse = function(options) {
var defaults = { closed: false }
settings = $.extend({}, defaults, options);
return this.each(function() {
var obj = $(this);
obj.find("legend").addClass('SmartFieldSetCollapsible').live("click", function() {
if (obj.hasClass('collapsed')) {
obj.removeClass('collapsed').addClass('SmartFieldSetCollapsible'); }
$(this).removeClass('collapsed');
obj.children().next().toggle("slow", function() {
if ($(this).is(":visible")) {
obj.find("legend").addClass('SmartFieldSetCollapsible');
obj.removeAttr("style");
obj.css({ padding: '10px' });
obj.find(".imgCollapse").css({ display: 'none' });
obj.find(".imgExpand").css({ display: 'inline' });
}
else {
obj.css({ borderLeftColor: 'transparent', borderRightColor: 'transparent', borderBottomColor: 'transparent', borderWidth: '1px 0px 0px 0px', paddingBottom: '0px' });
obj.find(".imgExpand").css({ display: 'none' });
obj.find(".imgCollapse").css({ display: 'inline' });
}
});
});
if (settings.closed) {
obj.addClass('collapsed').find("legend").addClass('collapsed');
obj.children().filter("p,img,table,ul,div,span,h1,h2,h3,h4,h5").css('display', 'none');
}
});
};
});
$(document).ready(function() {
$("fieldset.SmartFieldSetCollapsible").collapse();
});
The problem is that you are doing more then just a plain selector for your live selection
From api.jquery.com
"DOM traversal methods are not fully supported for finding elements to send to .live(). Rather, the .live() method should always be called directly after a selecton"
if (obj.hasClass('collapsed')) {
obj.removeClass('collapsed').addClass('SmartFieldSetCollapsible'); }
$(this).removeClass('collapsed');
First you want to remove the class an add another class if it has the class collapsed, an then you remove the class collapsed. I don't know if it affects the working of the system but it is worth to try.
Does the function work if you just use .click (when the field aren't updated)?
Traversing is the issue. You can solve it with a simple selection.
var obj = $(this),
obj.find("legend").addClass('SmartFieldSetCollapsible');
$('legend.SmartFieldSetCollapsible').live('click.collapsible', function(e){