javascript onclick function to enlarge text - javascript

I'm not sure why, but I can't seem to get this to work.
Here is my function to enlarge my font.
<script type="text/javascript">
function growText() {
var text = document.getElementById("t_left_text");
text.font-size=22px;
</script>
And here is where I call it
<div id="t_left" onclick="growText()">
<br />
<p id="t_left_text">Mountains are beautiful land structures <br /> that are a result of plate tectonics.</p>
<br />
</div>

Try:
text.style.fontSize = "22px";
DEMO: http://jsfiddle.net/C2MWN/
When you want to change an element's CSS, you need to use the style property. To determine the name of the specific style property, the CSS name is converted to camel case - "font-size" becomes "fontSize", so that the identifier is valid in JavaScript.
While setting the style properties definitely works, and although this is a very simple example, it might be easier to deal with adding and removing a class. This is especially useful when setting multiple CSS properties. The class could be defined as:
.enlarged-font {
font-size: 22px;
}
And you would manipulate the text.className property (and/or the classList property).
Depending on the browser you're using, you could have easily provided a better description (as obvious as it was for some of us) of the problem by using the JavaScript console in the browser. In Firefox, you could use Firebug. In Internet Explorer and Chrome, you could use Developer Tools. If installed/enabled, these can usually be brought up by pressing the F12 on your keyboard.
Also, don't forget to close your function with a }.
Reference:
style property: https://developer.mozilla.org/en-US/docs/DOM/element.style
classList property: https://developer.mozilla.org/en-US/docs/DOM/element.classList

Use below code
function growText() {
var text = document.getElementById("t_left_text");
text.style.fontSize ="22px";
}
Working example http://jsfiddle.net/D2anZ/

Here's a version that uses CSS to accomplish what you want. That way if you want to do this to different sets of text at the same time, and want to change that font size, there's only one place you need to make the change. (Or if you also want to add other css properties (color, etc.)
Fiddle
JavaScript
function growText() {
var text = document.getElementById("t_left_text");
text.className = 'large-font';
}
CSS
.large-font {
font-size: 22px;
}

Related

How do I removeAttribute() hidden from p2? doesn't seem to do anything as is

I'm trying to change the attribute of an object with removeAttribute to take away the hidden status of it but so far nothing seems to work.
My code seems to have no effect. Am I doing something wrong?
function changePage() {
document.getElementById.("p2");
p2.removeAtribute.("hidden") ;
}
I've also tried it all on one line as well like so
function changePage() {
document.getElementById.("p2").p2.removeAtribute.("hidden") ;
}
I've never seen the use of dots before opening parentheses.
E.g.
document.getElementById.("p2").p2.removeAtribute.("hidden") should be document.getElementById("p2").removeAtribute("hidden")
(You are also referencing the element by id after you just retrieved it, which is unnecessary.)
Your first example didn't work because you retrieved the element and did nothing with it, then tried to access a p2 variable that wasn't declared. Again, you also have the . before parentheses.
Here's the js example:
function changeVisibility()
{
var p2 = document.getElementById('p2');
switch (p2.style.visibility)
{
case 'hidden':
document.getElementById('p2').style.visibility = 'visible';
break;
case 'visible':
document.getElementById('p2').style.visibility = 'hidden';
break;
}
}
<div id="p2" style="visibility:hidden">
test
</div>
<br />
<button onclick="changeVisibility()">
change visibility with basic js
</button>
And here's the jQuery example:
function changePage()
{
$('#p2').toggle();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="p2" style="display:none">
test
</div>
<br />
<button onclick="changePage()">
change visibility with basic js
</button>
The basic JS version uses the visibility style, and you can see that it doesn't collapse the element, it only makes it invisible.
jQuery has a nice built-in .toggle function that changes the display of the element. If it is hidden, it collapses the element. When the element is displayed, it is re-assigned whatever the display style is for that element. Building that in basic js would take a lot more work, as you are then tracking state (if you want to make the method reusable). You can make jQuery work similarly to the basic js version if you use the css properties, but toggle is quite nice and simple.
Your main issue is that you were mixing the getting of the element with methods that are only available on jQuery objects. I suggest reading the jQuery tutorials for basic accessors, which can get elements by id, class name, etc.

Getting a field from a named CSS style in Javascript

I have an HTML document with a link tag in its head to a particular CSS stylesheet:
<link rel="stylesheet" href="style.css" type="text/css">
This .css file contains a particular class, like so:
.mystyle {
color: #00c;
}
What I'm trying to do is to grab that class's color field, so that I can use it dynamically in another part of the page (for another element's background-color). Is there any way in a JavaScript program to access that information, by the name of the class? Something like this:
var myColor = document.getStyle(".mystyle").color;
Some caveats:
There may or may not be other stylesheets that are also linked from this HTML document.
There may or may not be any particular elements on the page that are styled with this particular class.
I've already tried setting a temporary element to have the given class, and then grabbing its color field. That didn't work: the color field contains the empty string.
Thanks.
You can get all stylesheet information using the StyleSheetList and related objects.
In the example below, I aggregate all the document's styles (i.e., inline styles, an external bootstrap stylesheet and the stylesheet provided by Stackoverflow), and retrieve the color information for the .mystyle class:
const sheets = [...document.styleSheets];
const rules = sheets.reduce((a, v) => [...a, ...v.cssRules || []], []);
const rule = rules.find(r => r.selectorText === '.mystyle');
console.log(rule.style.color);
.mystyle {
color: #00c;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
It's possible to use JavaScript to read the actual CSS files themselves by scraping the DOM and extracting the relevant information. While possible, it's clunky, and I'd advise against that unless absolutely necessary. If it's required, this answer covers it pretty well.
As an alternative to scraping the header information, you could use HTMLElement.style and grab the color value, though note that this will only work for inline styles:
var span1 = document.getElementsByTagName('span')[0];
var span2 = document.getElementsByTagName('span')[1];
// Empty
console.log(span1.style.color);
// Blue
console.log(span2.style.color);
.mystyle {
color: #00c;
}
<span class="mystyle">Text</span>
<span style="color: #00c;">Text</span>
However, a much better solution would be making use of what are known as CSS variables. These are defined in :root with a double hyphen prefix, and can be referenced with var(). This allows you to only set a colour once, and re-use it for both a color property and a background-color property, as can be seen in the following:
:root {
--colour: #00c;
}
.a {
color: var(--colour);
}
.b {
background-color: var(--colour);
}
<span class="a">Text</span>
<span class="b">Text</span>
Hope this helps! :)
Try window.getComputedStyle in combination with getPropertyValue.
var elem = document.getElementsByClassName("mystyle");
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("color");
More: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
For any who might come after me:
One can indeed use window.getComputedStyle(element) on an element. However, creating your own element first (if one doesn't exist) comes with an important caveat. Firefox will properly calculate the computed style. However, Chrome (and possibly Safari too) won't calculate the style of an orphaned element that isn't part of the DOM tree. So if you go that route, be sure to add it to the tree somewhere, possibly as a hidden element.

setting color of a link in javascript

I want to set the color of "val" in the link in below code.
var link = $('' + val + '<br><br>');//this is the link
link.style.color="red";//this is how iam trying to set the color of "val"
SO HOW TO EXACTLY DO IT.
You can do this:
link.css({ color: 'red' });
But the correct and nice way would be:
$(".parent_element").prepend(''+val+'<br><br>');
$(".parent_element > a:first").css({ color: 'red' });
Try this:
$(link[0]).css({ color: 'red'});
The reason for this is that link is not an <a> element - it's a set of elements: <a>, <br> and another <br>.
Another approach would be:
link.css({ color: 'red' });
but this will set this CSS to not only <a>, but both <br>'s as well (not a big deal though).
If you are using jQuery(which it does seem like) go ahead with this,
jQuery
link.css("color","red");
Otherwise,
JavaScript
link[0].style.color = "red";
What you did doesn't work because link is an array. Before applying a style to it, you have to first select the first element by link[0] and then operate on it.
You could use link.style.color="red" if link was an HTMLElementNode, but it isn't. It might be a jQuery object, but if you are using an older version of the library then it will return undefined.
First you need to fix your jQuery call. You can't create multiple elements at the top level. (You can skip this bit if you are using a sufficiently new version of jQuery).
Since there is no good reason to use a double <br> (it shouts "Use CSS to add a margin instead"), I've taken them out:
var link = $('' + val + '');
Now you have a jQuery object so you can either use the jQuery method of setting CSS:
link.css("color", "red");
or get the HTMLElementNode from the jQuery object and use that:
link.get(0).style.color="red";
link.css("color", "red")
However, I think it would be better to create a css class for that and set up the color there. In Javascript/jQuery I would just add the class to the tag when needed. It is more elegant.

How to read CSS property of Psuedo class in javascript

I've searched SO and googled for this and there are many answers on how to read CSS propeties but non that allow the reading of a pseudo class property.
I have used the following to allow me to easily reuse certain pages (firmware/config upload) on a number of products.
.productname:before
{
content: "My Shiny New Product";
}
then
<span class="productname" />
in the html to insert the correct name.
Currently when sending a Firmware update to the Server no check is done on the client browser and the server returns [please reboot to contunue...] or [this is not a [productname] update file]. As you can imagine the firmware updates can be quite large and if transfered over 3G take some time.
I want to get the productname from the CSS :before pseudo class to allow me to check the upload file name before send it. I have implemented this JS Fiddle to illustrate the issue.
I have tried putting the content property on the .productname class directly (as a copy placeholder) and FF, Opera and Safari will read this but you guessed it IE returns undefined.
I know I can use a global var in JS and might have to do that but I'd rather have it defined in one place to avoid potential mistakes.
So does anyone know how to (or workaround ) read properies of the :pseudo CSS classes?
Thanks in advance.
Update
Since i cant get a solution for IE8, I've changed to using the following code instead.
window.addEvent( "domready",
function()
{
window.productName = "My Shiny New Product";
var def = '.productname:before { content: "'+window.productName+'"; }';
var style = new Element("style");
style.setAttribute( "type", "text/css" );
if( style.styleSheet )
{
style.styleSheet.cssText = def;
}
else
{
style.innerHTML = def;
}
document.getElementsByTagName("head")[0].appendChild(style);
document.getElementsByTagName("head")[0].appendChild(style);
} );
with reference to this site Dynamic SCRIPT and STYLE elements in IE
you can use window.getComputedStyle. however, an answer notes that some browsers may not support this, so tread lightly. here's a demo
<span class="test" />
<span class="test" />
<span class="test" />
.test:before{
content: "My Shiny New Product";
}
$(function() {
//get all element class test
var test = $('.test');
//each of them, alert the content
test.each(function() {
var style = window.getComputedStyle(this, "before");
alert(style.content);
});
});​

Javascript getElementById()

I'm trying to create a generic javascript function that would change attributes on events.
The way it would work is
function fooFunction(sourceElement)
{
var newName = sourceElement+'Span';
var newElement = document.getElementById(newName);
//Important line
newElement.property = "enter properties here";
}
and I'd call it with something like
<img src="foo.gif" id="foo" name="foo" onmouseover="fooFunction(this.id);"/>
<span id="fooSpan" name="fooSpan">some text here</span>
So in theory, when hovering the image, it should change whatever propery I need to change on the fooSpan object. It works in Opera, but on IE it returns a null object.
Any ideas ?
The idea would be that I would have multiple images that would automatically trigger the property change on the associated text span (typically the css style).
Are you sure you're getting the ID properly in IE? Maybe the ID being passed in is null in IE (perhaps this.id isn't working?).
Try calling it like this:
<img src="foo.gif" id="foo" name="foo" onmouseover="fooFunction('foo');"/>
and see if that helps. I don't see any reason why getElementById() would fail, so the only thing I can think of is that it's an ID issue.
May be this line won't work in IE. "newElement.property"
I don't know the exact reason.
You can use this instead of that line
newElement.setAttribute(property,"enter properties here");
In the mean time, i am trying to find out the reason behind the error.
My suggestion would to do something like this.
function fooFunction(sourceElement,property,propertyValue) {
var newElement = document.getElementById(sourceElement);
newElement.setAttribute(property,propertyValue);
};
And your HTML would look like:
<img src="foo.gif" id="foo" name="foo"
onmouseover="fooFunction('fooSpan','class','mouseover_span');"/>
<span id="fooSpan" name="fooSpan">some text here</span>
I'd STRONGLY urge you to consider using jQuery's built-in attr() method which integrates the function you want perfectly across browsers and is incredibly easy to use.
Using your example, if you wanted to change the "src" property for "foo", you could do it in a single line of code:
$("#foo").attr("src","images/whatever.png");
Similarly, if you wanted to change the html WITHIN "fooSpan", all you'd have to do is:
$("#fooSpan").html("something else");
You can even tie these to events that are going to give you a lot more flexibility than the onmouseover property:
$(document).ready(function(){
$("#foo").mouseover(function(){
$("#fooSpan").html("something else");
$("#foo").attr("src","images/whatever.png");
});
});

Categories