Javascript: How to check whether an element is "displayed" on the screen? - javascript

Step 1:
When I change the value of the display property of an element using JavaScript by something like:
document.getElementById("myDiv").style.display = "none";
it changes what I see in the browser, but it does not change anything in the server side HTML script.
Step 2 - Problem here:
The problem is that after the above step, I later have to check if #myDiv is displayed on the screen. If it is, I do something. So I need to use a conditional expression like:
if (document.getElementById("myDiv").style.display == "none") {
//do something here
}
But problematically this expression never evaluates to true, because step one did not change anything on the server side HTML.
So I need a way here to check in JS whether an element is displayed on the screen? How can I do that?
NOTE:- Don't suggest JQuery. I can't use it.

What you have should be working. Yes, running
[...].style.display = "none";
does not change the server-stored HTML; however, when you check for that same property,
([...].style.display == "none")
you are checking the inline styles, which are set by the first line.
For example, running
document.getElementById("aDiv").style.display = "none";
Will set the inline style property of #aDiv:
<div id="aDiv" style="display: none;">
JSFiddle

Use the visibility property.
visibility: visible|hidden|collapse|initial|inherit;
document.getElementById("myDiv").style.visibility = "hidden";

Related

Calling a value + style.display function?

I'm struggling to get this working because I don't know the right formatting.
What I am attempting is to get a CSS modal to display depending on what a user selects as a value in a Javascript applet.
The idea is to return .style.display = "block";
function onClick(event){
<something>.style.display = "block";
}
Where contains a value that has being saved in the format of intersects[0].object.title
So if for example I have selected "manhattan"
alert(intersects[0].object.title)
I'll get the string "manhattan" displaying correctly. That works perfectly.
But I can't get manhattan.style.display = "block"; returned and WORKING inside the function? I tried :
function onClick(event){
intersects[0].object.title.style.display = "block";
}
Also tried
function onClick(event){
(intersects[0].object.title).style.display = "block";
}
Any help would be greatly appreciated
This may not be directly what you're looking for, but it may help anyways. To make it work in your case, just change the button press to be a check for the selected value.
Rather than adjusting the CSS directly, this route modifies the element's classList to remove or add a .hidden class that contains the correct CSS.
// Loop through all modal buttons
document.querySelectorAll('.modal-button').forEach(function(element) {
// Add a click event listener to all modal buttons
element.addEventListener('click', function() {
// Toggle the target modal on click
toggleModal(element.dataset.target);
});
});
// Create the function to toggle the modals
function toggleModal(target) {
// Find the target
let targetElement = document.querySelector(target);
// Check if the target is hidden
if (targetElement.classList.contains('hidden')) {
// If it is, show it
targetElement.classList.remove('hidden');
} else {
// If it isn't, hide it
targetElement.classList.add('hidden');
}
}
.hidden {
display: none;
}
<button data-target="#modal" class="modal-button">Toggle Modal</button>
<div id="modal" class="hidden">Hey there, I'm a modal!</div>
I'm not certain from your question how the pieces of your puzzle are related to one another, and it would be helpful if you could clarify by showing more of your HTML and Javascript code, but I'll toss a couple of ideas at you in the meantime. Apologies if I'm telling you stuff you already know.
The only sort of object you would usually be able to set "style.display" on is an HTML element. To tell Javascript which HTML element you want to modify, you usually use a CSS selector like "document.getElementById('myDiv')"
It sounds like "manhattan" might be a piece of information you could use to uniquely identify the HTML element you intend to show. If so, there are four simple parts to showing the correct element:
associate the element with that particular string (eg via an id)
get the string at runtime (the same way as you did for the alert)
select the element based on the matching string
display the selected element
All together, it might look like this:
<div id="manhattan"></div>
<script>
var identifier = intersects[0].object.title;
alert(identifier) //I'm assuming this alerts "manhattan"
var elementToShow = document.getElementById(identifier);
elementToShow.style.display = "block";
</script>
Is this on the right track? If not, just provide more detail, and I'll see what else I can suggest.
Give to you div some id and then just change that:
<div id="test"></div>
document.getElementById("test").style["display"] = "block";
or
document.getElementById("test").style.display = "block";
or
document.getElementById("test").style.setProperty('display', 'block');
or
document.getElementById("test").setAttribute('display', 'block');

How to change CSS file or hide <link> tag

I want to change the design of my site by changing the CSS file attached. I have tried with script when the link is with id "link"
var x = document.getElementByID ("link")
X.href = style2
It didn't work.
The other thing I tried was to hide the <link> tag which had class "linkclass"
<style>
link.linkclass {
visibility:hidden;
}
</style>
But it didn't work either.
Can someone help.
Sorry if the code is bad formatted but I can't get how to format code in stack overflow
Three things wrong with this:
javascript is case sensitive. That means X is a different variable than x
style2 is not a valid URL. You have to use an URL to an existing .css file
<link> is not a visible element. Hiding an element that isn't visible in the first place accomplishes nothing.
This works:
var x = document.getElementByID("link");
x.href = "http://url/to/your/style2.css";
// ^ notice the lowercase x
If you wanna hide element (I got that impression from your examples), your javascript code should look like this:
var x = document.getElementById("link");
x.style.display = 'none';
Also take care with following:
-uppercase letters getElementbyId
-you're missing semicolon (;) after first expression
-your variable "x" is uppercase in second row("X").
In most cases this should be enough to disable element with CSS, just add this class (linkclass) to element which you want to hide:
<style>
.linkclass {
display: none;
}
</style>
You could do
$("#link").disabled = true;
This may also work.
document.getElementByID("link").disabled = true;
There is also another Stack question that addresses this here. Removing or Replacing a Stykesheet
update
You say you are trying to change the stylesheet. You could create a function to do it like this.
function styleSheetSwitcher( newFile ){
$("#link").prop("href", newFile);
}
styleSheetSwitcher("myNewCss.css");

Jquery script not working to alter CSS on change

I've added some custom elements to be included with my WooCommerce account page to be seen with the order history. Unfortunately the page is setup with tabs to only display the information pertaining to the active tab.
I'm not very familiar with jquery, but I thought it would be simple enough to use Jquery to hide the divs I added when the order history has a display of none.
I added the following script to my theme's main.js file:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
When the class .my_account_orders has a display of none it should change the div I added (.paging-nav) to have a display of none. But it just doesn't work.
Is there something wrong with this script or do I need to do something special to initiate it? Since it's in my theme's main.js file and I used $(document).ready(function() I figured it would just load with the page.
Any help with this would be greatly appreciated.
Instead of using:
var display = $('.my_account_orders');
Implement it into the if statement like this:
if($('.my_account_orders').css("display") == "none") {
Because originally it is trying to find a variable called $display, so it would return a syntax error of undefined.
You've got an errant $ in your if statement. This should work instead:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
Also keep in mind that your var display is only going to match the first element that has a class of my_account_orders, so if there are multiple elements with that class, and they don't all have the same display, you could get unexpected results.
Try this:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
I believe it's a very lame way to check for a css property such as display to determine if an element is hidden or not. With jquery, you can make use of :hidden selector which determines whether an element is hidden and return a bool value.
$(document).ready(function(){
if($('.my_account_orders').eq(0).is(":hidden")) // eq(0) is optional - it basically targets the 1st occurring element with class 'my_account_orders'
{
$('.paging-nav').css("display","none");
}
});
Example : https://jsfiddle.net/DinoMyte/sgcrupm8/2/

document.getElementById('').src == ??? (is equal to FAIL)

My javascript is
function changeImage(imgID) {
var baseurl = "media/images/";
if (document.getElementById(imgID).src == baseurl+"selection-off.png") {
alert('Success');
document.getElementById(imgID).src = baseurl+"selection-no.png"; }
else {
alert('Fail'); } }
and my HTML is
<div id="mustard" class="checkbox"><img id="mustard-img" class="no-off" src="media/images/selection-off.png" alt="checkbox" onClick="changeImage('mustard-img')" /></div>
I always get Fail when clicking the image. I must be missing something really elementary.
Some browsers convert the img src to the full url (including http://www....)
try alerting it to make sure..
You could use the
document.getElementById(imgID).src.indexOf( baseurl+"selection-off.png" ) >= 0
which checks if one string is contained in the other..
Alert string document.getElementById(imgID).src. It might be taking complete path i.e. including host name while the string you are comparing with has relative path.
I tried your code on my own server.
Result:
document.getElementById(mustard-img).src is
'http://localhost/webfiles/media/images/selection-off.png'
baseurl+"selection-off.png" is 'media/images/selection-off.png'
baseurl seems to show the relative url only.
So that is the reason why "Fail" gets alerted.
Try with the following code:
<div id="mustard" class="checkbox"><img id="mustard-img" class="no-off" src="media/images/selection-off.png" alt="checkbox" onClick="changeImage(this)" /></div>
<script>
function changeImage(img) {
if (img.src.indexOf('selection-off.png')) {
alert('Success');
img.src.replace(/selection-off.png/, 'selection-no.png');
}else{
alert('Fail');
}
}
</script>
The differences with your code:
passing the img reference: this instead of the id in the onclick function
use indexOf instead of ==, for relative paths
Are you sure the DOM is built when the script is loaded ?
It's because the src attribute is changed by the browser. Don't do it that way, the proper way to check and change the css class or style attribute instead.
Image-based checkboxes are quite common, but here is the full solution.
1) Render actual checkboxes first. These work for 100% of browsers.
2) When the page loads, place your "image checkbox" next to the checkbox and hide the checkbox
3) When the image is clicked, toggle the checkbox and use the hidden checkbox to ascertain the state of the image.
When the form is POST-ed, the checkboxes will act like normal checkboxes. If JavaScript is disabled or otherwise not available the form is still usable.

visibility:collapse in javascript

I'm using Ultrawebgrid for my applcation:
I'm using a textarea for listing the errors in my application in the row template when the user clicks that particular row...
So I need to have
texarea when there are any errors..... otherwise when there are no errors i dont even
want the row_template to pop up..... I'm using IE6.
I'm checking if there are any errors using javascript.so I had to use the javascript event handler:: UltraWebGrid1_BeforeRowTemplateOpenHandler(gridName, rowId, templateId)
where in I write the statements given below:
document.getElementById("TextArea2").style.visibility="collapse"
inside the above event function
1) it's showing javascript error as
"Couldnot get the visibility property:Invalid Argument"
but the row template does not pop up....... only the error's coming....
2) Is there any code to block the row template when there are no errors.??
i mean no pop_up for no errors
What's the solution for this???
DISPLAY
Use display instead of visibility. This occupies no space in your document.
document.getElementById("TextArea2").style.display = 'none'; // Turn off
document.getElementById("TextArea2").style.display = 'inline'; // Turn on
VISIBILITY
document.getElementById("TextArea2").style.visibility="hidden"; // Turn off
document.getElementById("TextArea2").style.visibility="visible"; // Turn on
By using the above code textarea won't be visible, but there will be blank space in your document having the height and width of the textarea.
Also 'collapse' value is supported only in Internet Explorer 8
Try using:
document.getElementById("TextArea2").style.display = 'none';
and (to turn it back on again)
document.getElementById("TextArea2").style.display = 'block'; // or 'inline'
You want:
document.getElementById("TextArea2").style.visibility = "hidden";
"collapse" is not a valid value for the visibility property in IE6, as your error message indicates.
Alternatively as suggested by #tvanoffsen you could set the display property to "none". This has a slightly different effect - it will not take up any space if set to "display: none", whereas setting "visibility: hidden" still takes up space.
use visible and hidden for .style.visibility attribute not block and hidden.
it works.

Categories