Hide an element without CSS - javascript

If CSS is disabled, but JavaScript is not, how can I hide an element (a file input field, in my case)? None of the following will work, although they all work when CSS is enabled:
element.style.display = 'none';
element.style.visibility = 'hidden';
element.hidden = 'hidden';
element.hidden = true;
element.setAttribute('hidden','hidden');
element.setAttribute('hidden',true);
The only thing that can hide when CSS is disabled, as far as I know, is a hidden input field. Maybe that could lead to a solution. Any help is appreciated, thanks!

Because it's an input element, you could change its type to hidden:
element.type = "hidden";
But be aware that this won't work in some IE versions. In that case, I think you'd need to create a new element, give it the hidden type, and swap them.
DEMO: http://jsfiddle.net/gLvRz/

You can just delete element from DOM:
element.parentNode.removeChild(element);
If you want to restore it later, you can store its HTML code (or a reference to element itself) in a variable. In case of form field, it may be required to store its value too and then restore the value after restoring element itself.
Also, consider using hidden HTML5-attribute, though its support by browsers may be not too wide yet (and the attribute itself may be removed from HTML standard).

I suppose you could abuse the AREA element to hide something inside it.
//hide element
var hiddenContainer = document.createElement("AREA");
element.parentNode.insertBefore(hiddenContainer, element);
hiddenContainer.appendChild(element);
//show element
hiddenContainer.parentNode.insertBefore(element, hiddenContainer);

Related

Disable a text area by it's class (not id)

I have 2 text area's that are generated automatically, and I need to use JavaScript to disable both when the page has loaded. The catch is because they are generated automatically I can't give them an ID because they would both have the ID - a big no.
Attempted Javascript:
document.getElementByClassName('option_window-size').disabled=true;
I know this works because if I change getElementbyClassName to ID then it will work if I give the text areas the ID as well. But as I say it needs to work off class. Also it can't work of the Name attribute because that is automatically generated per product and per page...
I have tried this but it just doesn't work and I can't figure out why not because it should as the only thing I have changed is from ID to CLASS
Text Areas
<textarea name="willbeautogenerated" class="option_window-size" cols="40" rows="5">willbeautogenerated</textarea>
Additional note: I have tried to count and assign them different IDs using PHP but it gets far to complex. Also it is only these two that need disabling, thus I can't just disable all text area's on the page.
I know this works because if I change getElementByClassName to ID then it will work if I give the text areas the ID as well. But as I say it needs to work off class.
getElementsByClassName returns a NodeList rather than a Node itself. You'll have to loop over the list, or if you expect just 1 item, choose index 0.
var nodes = document.getElementsByClassName("option_window-size"),
i = 0, e;
while (e = nodes[i++]) e.disabled = true;
jQuery makes this pretty simple:
$(".selector").prop("disabled", true);
ALTHOUGH! It should be noted that this note appears on the man pages for $.prop() and $.attr():
Note: Attempting to change the type property (or attribute) of an input element created via HTML or already in an HTML document will result in an error being thrown by Internet Explorer 6, 7, or 8.
This doesn't apply directly to your question, but you are changing prop/attrs on an input element, so be aware.
But it's still possible with plain old JS:
var els = document.getElementsByClassName("selector"); // note: Elements, not Element
for(var e = 0; e < els.length; e++)
{
els[e].disabled = true;
}
getElementsByClassName returns an NodeList, you just have to iterate over each element within.
You can use class selector,
$('.option_window').attr('disabled', true);
OR
$('.option_window')[0].disabled = true;
With Jquery you can do:
//make sure to use .prop() and not .attr() when setting properties of an element
$('.option_window').prop('disabled', true);
Disable textarea using jQuery:
$('.option_window-size').attr('disabled', true);
your missing a s in elements and the index where the element is like [0], for the first element.
document.getElementsByClassName('option_window-size')[0].disabled=true;
or
document.getElementsByName('willbeautogenerated')[0].disabled=true;
Disabel texarea using .prop() methode in jquery...
$('.option_window-size').prop('disabled', true);
You can use CSS:
.option_window-size{display:none;}

Is there a way to detect if I'm hovering over text?

What I'm really after is to detect when the cursor changes to type "text", that is, when I'm hover over a piece of text. I have tried looking at the element types I am hovering over, but this isn't too accurate because I don't know what they actually contain.
I understand that detecting the CSS cursor attribute is only possible if it has previously been assigned by me.
Is this possible at all? How would you go about doing this?
EDIT:
I do not want to check If I am currently over a specific element, I want to know if I am hover over any text within that element. A div could be 100% width of the browser, but with a shorter piece of text at the far left. I don't want to detect when hovering over just any part of an element.
No need to try to detect if the cursor changed.
You can simply detect if the mouse is hovering your text by using this kind of construct :
document.getElementById('myTextId').onmouseover = function() {
// do something like for example change the class of a div to change its color :
document.getElementById('myDivId').className = 'otherColor';
};
If you don't have an id but a class or a tag, you can replace getElementById by getElementsByClassName or getElementByTagName (which will return arrays on which you'll iterate).
If you want to restore the color when leaving the element, I suggest you bind the event onmouseout in the same way.
For example, if you want to do something on any paragraph, you may do that :
var paras = document.getElementByClassName('p');
for (var i=0; i<paras.length; i++) {
paras[i].onmouseover = function() {
// do something like for example change the class of a div to change its color :
document.getElementById('myDivId').className = 'otherColor';
};
}
I you plan to do a lot of things like this, I suggest you look at jquery and its tutorial.
One possible way is to find all the text nodes in your DOM and wrap them in a span with a certain class. Then you could select that class and do whatever you want with it:
// Wrap all text nodes in span tags with the class textNode
(function findTextNodes(current, callback) {
for(var i = current.childNodes.length; i--;){
var child = current.childNodes[i];
if(3 === child.nodeType)
callback(child);
findTextNodes(child, callback);
}
})(document.body, function(textNode){ // This callback musn't change the number of child nodes that the parent has. This one is safe:
$(textNode).replaceWith('<span class="textNode">' + textNode.nodeValue + '</span>');
});
// Do something on hover on those span tags
$('.textNode').hover(function(){
// Do whatever you want here
$(this).css('color', '#F00');
},function(){
// And here
$(this).css('color', '#000');
});
JSFiddle Demo
Obviously this will fill your DOM with a lot of span tags, and you only want to do this once on page load, because if you run it again it will double the number of spans. This could also do weird things if you have custom css applied to spans already.
If you're using jQuery (which you should, because jQuery is awesome), do this:
$("#myDiv").mouseover(function() {
$("#myDiv").css("background-color", "#FF0000");
});

Is there a CSS :visible (scroll) selector?

I want to change the style of visible elements using CSS only. Is there a selector that does it? It needs to work with Chrome and Firefox only. (I am building an extension / addon)
If there isn't, is there a way to change the style of visible elements with a light javascript?
Visible within the current scroll position. An element can be out of the scroll vision, or partially visible.
There is no standard pure CSS rule for assessing visibility.
As others have said, jQuery (if you wanted to use jQuery) has both a CSS selector extension :visible and the ability to execute .is(':visible') on any given jQuery object to get the computed style on any given DOM element with .css("display") or .css("visibility").
It's not particularly simple in plain javascript to determine if an object is visible because you have to get the computedStyle (to take into account all possible CSS rules that might be affecting the element) and you have to make sure no parent objects are hidden causing the child element to be hidden. This is a function I have in my own personal library:
//----------------------------------------------------------------------------------------------------------------------------------
// JF.isVisible function
//
// Determines if the passed in object is visible (not visibility:hidden, not display: none
// and all parents are visible too.
//
// Source: http://snipplr.com/view/7215/javascript-dom-element-visibility-checker/
//----------------------------------------------------------------------------------------------------------------------------------
JF.isVisible = function(obj)
{
var style;
if (obj == document) return true;
if (!obj) return false;
if (!obj.parentNode) return false;
if (obj.style) {
if (obj.style.display == 'none') return false;
if (obj.style.visibility == 'hidden') return false;
}
//Try the computed style in a standard way
if (window.getComputedStyle) {
style = window.getComputedStyle(obj, "")
if (style.display == 'none') return false;
if (style.visibility == 'hidden') return false;
} else {
//Or get the computed style using IE's silly proprietary way
style = obj.currentStyle;
if (style) {
if (style['display'] == 'none') return false;
if (style['visibility'] == 'hidden') return false;
}
}
return JF.isVisible(obj.parentNode);
};
There is no pure CSS way of doing this. As Kirean's comment already said, why would you want to style visible elements only? Invisible elements won't show their styling anyway. If you don't want the invisible element to take up space (aka, laid out), you should use display: none;
If you REALLY want a selector to select the visible elements, you could do what Widor suggested and use jQuery. You could first use jQuery to first select the visible elements, add a class to them, then use CSS to select the elements by that class.
$('div:visible').addClass('visibleElement');
.visibleElement {
color: red;
}
There is no Way to select invisible elements, using pure CSS
http://www.w3.org/TR/selectors/
However, if you have a class name or other selector, using jquery you can do something like the following
jQuery(selector).each(function(){
Var $this=$(this);
if ($this.css('visibility')==='hidden')
//set your style
})
Edit: after your edit, there is definitely no way of selecting what is within the viewport with CSS alone. It is a context free language of sorts.
However, you can always fool around with an elements offset position with jquery and determine if it's within the current viewport(window.scrollposition or something similar). This type of solution gets messy quickly, though.
This looks like a :visible selector to me:
http://api.jquery.com/visible-selector/
EDIT: Saw your javascript tag before your 'no CSS' caveat.
But this is a CSS selector of sorts.

Select HTML Elements Visually

An HTML webpage is rendered in div. How can I allow the user to click and select any HTML tag? Similar to how Firebug and Chrome does it. I need the selected tag returned as is.
Add an event listener on your div and check for the event's target property (srcElement for IE).
document.getElementById("page").onclick = function(e) {
var target = e.target || e.srcElement;
alert(e.target.tagName);
};
http://jsfiddle.net/Xeon06/e67qW/1/
In jQuery:
$.click( function(){
var clicked = $(this);
});
you can add a onclick attribute to each html element which returns itself.
Chrome and Firefox also have a hover which outlines the element tough. To make that in a easy (and ugly) way you could add a hover css pseudo class for the html elements which adds a border of 1px to the html element.
*:hover{
border: 1px solid;
}
A better way would be to create a new element with javascript with the same measurements and position and to give it a z-index so it floats above the existing element

How to hide a div with jQuery?

When I want to hide a HTML <div>, I use the following JavaScript code:
var div = document.getElementById('myDiv');
div.style.visibility = "hidden";
div.style.display = "none";
What is the equivalent of that code in jQuery?
$('#myDiv').hide();
or
$('#myDiv').slideUp();
or
$('#myDiv').fadeOut();
$("#myDiv").hide();
will set the css display to none.
if you need to set visibility to hidden as well, could do this via
$("#myDiv").css("visibility", "hidden");
or combine both in a chain
$("#myDiv").hide().css("visibility", "hidden");
or write everything with one css() function
$("#myDiv").css({
display: "none",
visibility: "hidden"
});
Easy:
$('#myDiv').hide();
http://api.jquery.com/hide/
If you want the element to keep its space then you need to use,
$('#myDiv').css('visibility','hidden')
If you dont want the element to retain its space, then you can use,
$('#myDiv').css('display','none')
or simply,
$('#myDiv').hide();
$("myDiv").hide(); and $("myDiv").show(); does not work in Internet Explorer that well.
The way I got around this was to get the html content of myDiv using .html().
I then wrote it to a newly created DIV. I then appended the DIV to the body and appended the content of the variable Content to the HiddenField then read that contents from the newly created div when I wanted to show the DIV.
After I used the .remove() method to get rid of the DIV that was temporarily holding my DIVs html.
var Content = $('myDiv').html();
$('myDiv').empty();
var hiddenField = $("<input type='hidden' id='myDiv2'>");
$('body').append(hiddenField);
HiddenField.val(Content);
and then when I wanted to SHOW the content again.
var Content = $('myDiv');
Content.html($('#myDiv2').val());
$('#myDiv2').remove();
This was more reliable that the .hide() & .show() methods.
$('#myDiv').hide() will hide the div...
$('#myDiv').hide(); hide function is used to edit content and show function is used to show again.
For more please click on this link.

Categories