How do I compare css style values using JavaScript if conditions? - javascript

I got a quick question. If I want to compare a style left / right value with another coordinates (lets say mouse) how do I do it?
Here is what I tried without mouse coordinates but for some reason my condition never executes...
<style>
#container
{
position:absolute;
left:400px;
top:200px;
}
</style>
<script>
function moveExit(){
var containerId = document.getElementById("container").style;
if(containerId.left == 400 + "px")
containerId.left = 395 + "px";
}
</script>
And here is my body:
<body>
<div id="container">
<img
src="Images/image.jpg"
onmouseover="moveExit();"
/>
</div>
</body>
This is my first time playing around with javascript.. Thanks!

you need to use computed style for this purpose.
How do I get a computed style?
var left = window.getComputedStyle(document.getElementById("container")).left
for IE8 you have to use currentStyle proeprty as computed style is not supported.
document.getElementById("container").currentStyle.left
Cross-browser (IE8-) getComputedStyle with Javascript?

Try something like this:
http://jsfiddle.net/xtJA4/
$(document).ready( function() {
$("#container").mouseleave(function() {
if ($(this).css("left")=="400px") {
alert("Left = 400px");
}
});
});
There are of course changes that can be made to this, but for what you're needing this should work fine. You can of course go and change the alert() function to match what you need (modifying the left offset), but hopefully this helps!

While I'm not 100% sure what exactly you are looking to accomplish, here are a few comments, and suggestions for your code.
Rather than user javascript, I would use jQuery. This is something that David has suggested previously. One of the great advantages of jQuery is that it gets around most browser incompatibility issues.
To do this with jQuery you'll need to import jquery, and then you can use it like so:
<script type="text/javascript" src="./jquery/jquery.js"></script>
<script type="text/javascript">
function moveExit(){
var $element = jQuery('#container');
$element.css('left', '350px');
}
</script>
Please also notice that I have added the "type" attribute to the script elements.
As a side-note I would also remind you to add "alt" attributes to img elements. Good for accessibility and for when the images are blocked for whatever reason.
With greater understanding about what you are trying to accomplish a better answer can be provided.

Related

Show random div onclick

I am making a little project. For this project I want to be able to show a div to visitors of my site. However, I want my content to be varying. I've created three divs, all with a different id. When someone enters my site, I want him/her to see just one of the three divs. I've created some code that I thought would do the trick, but obviously it did not. I would really appreciate it if someone could tell me where I'm doing it wrong.
HTML
<div id="one">
1
</div>
<div id="two">
2
</div>
<div id="three">
3
</div>
<input type="button" id="Button" value="Random" onclick="RandomDiv();" />
CSS
#one {
display:none;
}
#two {
display:none;
}
#three {
display:none;
}
JAVASCRIPT
function RandomDiv() {
var myarray= new Array("one","two","three");
var ChosenDiv = myarray[Math.floor(Math.random() * myarray.length)];
alert(ChosenDiv); //Just to show this.
document.getElementbyId(ChosenDiv).style.display="inline-block";
}
Now, the alert seems to work fine, so that means that there is no problem in deciding the "ChosenDiv" (one, two or three). However, when I want to make that chosen div visible (display:none -> display:inline-block), it simply won't do this. I tried to use Google Chrome for defining the problem, but I can't tell what the problem is.
Why do answers always have to be so overcomplicated?
Just run the code, check your console and find out that you're using getElementbyId and not getElementById with a capital b, it's basic problem solving?
TypeError: document.getElementbyId is not a function[Learn More] script.js:6:5
jQuery is way to much to put into your project to simply edit some CSS or select some simple elements, if you ask me.
Using jQuery can help with changing CSS in javascript.
See http://api.jquery.com/css/ for more information on how to use this.
function RandomDiv() {
var myarray= new Array("one","two","three");
var ChosenDiv = myarray[Math.floor(Math.random() * myarray.length)];
alert(ChosenDiv); //Just to show this.
document.getElementById(ChosenDiv).css("display":"inline-block");
}
Don't forget to include jQuery in your code!
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
Just use a new function to call the display, lumping it in with your randomiser is one way to get a whole mess of bugs, and as previously mentioned, it seems you need to check your capitalisation, it's important
You could convert values in your array to this format:
var myarray= new Array("#one","#two","#three");

NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument arg 0 [nsIDOMWindow.getComputedStyle] (Followup)

Ok so I finally figured out which part of my code is causing the exception. You can read the initial post here. The code in the initial post is missing the part which is actually causing the exception (the manual subscription to the viewPortData observable). Apparently, I'm doing it wrong somehow... Here's the code:
self.viewPortData = ko.observable();
self.viewPortData.subscribe(function (newValue) {
var viewPort = $('#metro-view-port');
if (viewPort && newValue) {
self.fadeInOut(viewPort, newValue);
}
});
self.fadeInOut = function (domObject, newContent) {
if (newContent) {
var currentContent = domObject.html();
if (currentContent) {
var wrappedContent = $(currentContent);
wrappedContent.fadeOut(400, function () {
wrappedContent.empty();
domObject.html(newContent).hide().fadeIn(400);
});
} else {
domObject.html(newContent).hide().fadeIn(400);
}
}
};
So where did I go wrong?
The same error occurred to me. The problem was caused because the HTML had comments on it. Something like:
<!-- Some Comment goes here -->
<div>
...
</div>
To fix that, without changing the HTML, you need to wrap the HTML with something else, so you pass only one element to jQuery:
var div = document.createElement( 'div' );
div.innerHTML = nativeHtml;
var $html = $( div );
I created a fiddle using your code from this post and the previous post, and it works as it should.
However, I'm only returning a simple <div> tag to populate the HTML of the metro-view-port <div>.
My best guess is that the HTML that you're returning is the problem.
My advice to you is to first confirm this by reducing the HTML returned to something very simple, and then gradually reintroduce the intended code until you find the problem.
Flip your fadeIn(400) to a show().
It is simpler for jQuery to do the math for.... I think that it can't get computed style of the elements due to some floats inside it or something.
I had the same problem..... but after some research I got to here (DAMMET I LOST THE TAB - it was a jQuery bug report anyway ) and realised what needed to be fiddeled with to fix it.
In my code I swapped out fadeIn() to show() so it isn't to do with the animation
you would have thought that without the animation the problem wouldn't be prevalent either - but it is.
try slideDown(0 if your still after an animation, it might not work but its worth a pop.
This bug was in old versions of jQuery. Try to change .hide() to .css('display', 'none')
According to this jQuery bug, the problem may have to do with newline characters and whitespace text nodes in your HTML. In my case, I was taking a template like this one:
<script id="myTemplate" type="text/template">
<div>
<h2>Important stuff</h2>
</div>
</script>
And parsing it like this:
var currentContent = $.parseHTML($('#myTemplate').html());
So I ended up with a bunch of text nodes representing the newline and whitespace characters in the original HTML template. Probably something similar has happened to you.
To fix this, I stripped out the newlines and whitespaces like so:
$('#myTemplate').html().replace(/\n/g, '').replace(/>\s+</g, '><').trim();
Hope that helps someone!

Is there anyway to use javascript get the attributes determined by CSS?

For example,
<html>
<head><link rel="stylesheet" type="text/css" href="theme.css"></head>
<body>
<img id="tmp"></img>
</body>
</html>
in theme.css
img#tmp{
width:120px;
top:0;
left:0;
}
Is there anyway that I can get the width of the image "tmp" directly by JavaScript? Something like
var temp=document.getElementById("tmp"); var width=temp.style.width?
Here you go:
getComputedStyle( elem ).getPropertyValue( 'width' )
where elem is the DOM element.
Live demo: http://jsfiddle.net/7h4cg/
Btw, some older versions of some browsers do not support this code. If you need a cross-browser solution, use a cross-browser library.
You'll definitely want JQuery's help on this. Here is the list of all JQuery functions that can help you access all the style information you would want (hopefully).
Btw, if you're not familiar with some sort of Javascript library, it's probably a good idea to learn one.
I 2nd Nadir's motion, however in your direct example you can change your code to:
var temp=document.getElementById("tmp");
var width=temp.style.width;
In your own example, you have used the getElementById incorrectly by pluralizing it.
This comment sums up why.
What you're after is the computed style of the element. As usual, IE6-8 does it differently, so we need to do some sniffing:
var getStyle = window.getComputedStyle ? function (elem, prop) {
var styles = getComputedStyle(elem, null);
return prop ? styles[prop] : styles;
} : function (elem, prop) {
return prop ? elem.currentStyle : elem.currentStyle[prop];
};
This is my cross-browser inline function:
function getComputedStyle(elem, styleAttr){
return (elem.currentStyle ? elem.currentStyle : document.defaultView.getComputedStyle(elem, null))[styleAttr];
}
Some browsers will return the literal style width and height, as it was written in the css- pehaps as a pecentage or an em multiple, while others translate all style dimensions to pixels.
In this case, I'd use document.getElementById('tmp').offsetWidth to be sure to get the rendered width in pixels, no matter how it was assigned.

How can I show an element that has display: none in a CSS rule?

I have a really simple external css stylesheet that has the following :
div.hideBox {
display:none;
}
So when the html page loads, the div with that class attribute 'hideBox' will not show on the page, which is what I want. But I the box to show/appear when a user clicks on a button on that same page. I tried to use the onclick event to do this, but the div won't show.
So for example, the code would be :
<script language="javascript">
function showmydiv() {
document.getElementById('mybox').style.display = "";
}
</script>
</head>
<body>
<div id="mybox" class="hideBox">
some output of text
</div>
<input type="button" name="ShowBox" value="Show Box" onclick="showmydiv()">
What's strange is that a setup similar to this works when I use visibility:hidden; position:absolute; and I can use a JavaScript function to show the <div>.
What am I doing wrong here?
Because setting the div's display style property to "" doesn't change anything in the CSS rule itself. That basically just creates an "empty," inline CSS rule, which has no effect beyond clearing the same property on that element.
You need to set it to something that has a value:
document.getElementById('mybox').style.display = "block";
What you're doing would work if you were replacing an inline style on the div, like this:
<div id="myBox" style="display: none;"></div>
document.getElementById('mybox').style.display = "";
document.getElementById('mybox').style.display = "block";
try setting the display to block in your javascript instead of a blank value.
I can see that you want to write you own short javascript for this, but have you considered to use Frameworks for HTML manipulation instead? jQuery is my prefered tool for such a task, eventhough its an overkill for your current question as it has SO many extra functionalities.
Have a look at jQuery here

Toggle CSS values using Javascript

I'm trying to modify the behavior of some web parts in Sharepoint (thus forcing IE down my throat) for our users who use the Project server pages. I'm not really the best JavaScript guy, and this is driving me nuts.
On one webpart to display the work from Project, there is a subrow 'Planned' shown below the actual data entry row that clutters the view. We want to turn the 'Planned' row off.
I can do it with a simple three liner like this:
<style type="text/css">
.XmlGridPlannedWork {display:none;}
</style>
But the users want to toggle the lines on and off.
So I thought I'd try reading then writting the current CSS value like so:
<script type="text/javascript">
function toggle_PlannedLine()
var ObjPlanned = Document.getElementById("tr").getElementsByTagName("XmlGridPlannedWork");
for(var i=0;i<ObjPlanned.length;i++)
{
if (OjbPlanned[i].display != "none")
{
// toggle the 'Planned' line off
ObjPlanned[i].style.display = "none";
}
else
{
// toggle the 'Planned' line on
ObjPlanned[i].style.display = "inline";
}
}
return;
}
</script>
<button onClick="toggle_PlannedLine();">Toggle Planned Line</button>
The actual segment I'm targeting looks like this:
<tr class="XmlGridPlannedWork" RowID="694810f9-e922-4321-9236-e495dd5048d9B" ID="GridDataRow">
Of course, when you click the button, the rows don't disappear.
At this point, I'm pretty sure I'm missing something obvious, but like I mentioned, I'm no JavaScript guru.
Easiest Solution
Ok, so my answer below should help you out, but here is another way to approach it that is much simpler:
CSS
<style type="text/css">
.XmlGridPlannedWork {display:none;}
body.showPlanned .XmlGridPlannedWork { display: block}
</style>
HTML/JavaScript
<script type="text/javascript">
function toggle_PlannedLine() {
if(document.body.className.match(/\bshowPlanned\b/) > -1)
document.body.className = document.body.className.replace(/\bshowPlanned\b/,'');
else
document.body.className += " showPlanned";
}
</script>
<button onClick="toggle_PlannedLine();">Toggle Planned Line</button>
Original Answer
You were really close in the concepts you wanted, but as the other answers point out a number of things were missing. I rewrote your function to work cross browser, and please ask if you have any questions about it:
<script type="text/javascript">
function toggle_PlannedLine() {
var objs = [];
if( document.querySelector){
objs = document.querySelectorAll('tr.XmlGridPlannedWork');
} else if (document.getElementsByClassName) {
objs = document.getElementsByClassName('XmlGridPlannedWork');
} else {
var temp = document.getElementsByTagName('tr');
for(var j = 0; j < temp.length; j++){
if(temp[j].className.match(/\bXmlGridPlannedWork\b/) > -1){
objs.push(temp[j]);
}
}
}
for(var i=0;i<objs.length;i++)
{
if (objs[i].style.display != "none")
{
// toggle the 'Planned' line off
objs[i].style.display = "none";
}
else
{
// toggle the 'Planned' line on
objs[i].style.display = "inline";
}
}
}
</script>
<button onClick="toggle_PlannedLine();">Toggle Planned Line</button>
For those arguing that jQuery is not a valid answer, please take the following code as an example of why jQuery is so easy to use. All of the previous code is summed up like this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(function(){
$('button.toggle').click(function(){
$("tr.XmlGridPlannedWork").toggle();
})
})
</script>
<button class="toggle">Toggle Planned Line</button>
You forgot the opening brace for your function.
You are using getElementByTagName incorrectly. This function gets elements that match based on tag name (a, img, etc.) not CSS class. You can use jquery to accomplish what you want, or you can enumerate through every element on the page until you find the one you want. There are some open-source implementations of this available online. Your best bet, though, would be to add an id to the tag you care about, and then use getElementById.
Finally, Document should be document, and JavaScript is case sensitive.
Hope this helps!
document.getElementsByTagName looks for elements based on the name of their HTML tag, not their class attribute. Newer (not IE) browsers have support for document.getElementsByClassName(), and there are open source functions that do the same thing, falling back on the browser-native versions where available. This function will return a NodeList containing all the elements that use that class, and you can access each element and hide it through that list.
First, document should be lowercase in your var ObjPlanned declaration.
Second, getElementById returns an element based on a unique ID and you're passing it the element, or tag, name. getElementsByTagName returns an array of elements matching a certain tag but you're passing it a className. There is no 'getElementsByClassName' built in to JavaScript, but you can easily use Google to find a solution.
Use jQuery. It provides a very useful $.css() method, which does what you're looking for in a very simple fashion.

Categories