Suppose I have the following html:
...
<div class="thinger">...</div>
<div class="thinger">...</div>
<div class="thinger">...</div>
...
I want to dynamically set the width of all of the thinger divs. I know that I can do it like this:
$(".thinger").css("width",someWidth);
This will result in html that looks like this:
<div class="thinger" style="width: 50px;">...</div>
<div class="thinger" style="width: 50px;">...</div>
<div class="thinger" style="width: 50px;">...</div>
I would prefer to have the resulting HTML look like this:
...
<style>
.thinger {
width: 50px;
}
</style>
...
<div class="thinger">...</div>
<div class="thinger">...</div>
<div class="thinger">...</div>
...
I looked around but didn't see a jQuery utility to add/update/modify existing css classes. Does this exist?
I know that I could add it manually using something like this:
var styleElement = document.createElement('style');
styleElement.type = "text/css";
styleElement.innerHTML = ".thinger {width:" + maxWidth + ";}";
document.getElementsByTagName('head')[0].appendChild(styleElement);
But I don't want to have to deal with browser inconsistencies and I want to make sure I am doing things "the jQuery way". Any reason to choose one method over the other?
You can create the style element and append it to the head as you would any other element in the DOM, however it's a waste of time.
The best method to use would be to setup your class rule in a stylesheet and add the class to those elements. This maintains a better separation of concerns which is beneficial for both code reuse and maintenance later on.
I can't setup the class rule in a stylesheet because I don't know what the width will be prior to runtime.
In this case the current method you have of using css() is the best available.
Well that is a whole process read Add Rules to Stylesheets with JavaScript
Interesting question, it would be good to test if there is any performance benefit for using one approach over the other.
$("<style>.thinger{width:" + maxWidth + ";}</style>").appendTo("head");
If you need to update the value over time you should not keep appending new style tags to the page. Instead you'd want to update the existing one with something like this:
http://jsfiddle.net/daniellmb/0u5ffasq/
$('button').click(function(e) {
// get the dynamic width setting
var maxWidth = $(e.target).text(),
newRule = '.thinger{width:' + maxWidth + ';}';
styleTag = $('#thinger-style');
if (styleTag.length) {
// update existing
styleTag.text(newRule);
} else {
// create for the first time
$('<style id="thinger-style">' + newRule + '</style>').appendTo("head");
}
});
Yes there is. You can add or remove classes with jQuery .addClass() and .removeClass() methods.
$('#myDiv').addClass('myFirstClass');
or
$('#myDiv').removeClass('myFirstClass');
You can also use .css() method to update the css of an element like:
$('.myFirstClass').css('width','100px');
Related
I have a template:
function useIt() {
var content = document.querySelector('template').content;
// Update something in the template DOM.
var span = content.querySelector('span');
span.textContent = parseInt(span.textContent) + 1;
document.querySelector('#container').appendChild(
document.importNode(content, true));
}
<button onclick="useIt()">Use me</button>
<div id="container"></div>
<template>
<div>Template used: <span>0</span></div>
<script>alert('Thanks!')</script>
</template>
You can try the code here.
This code basically copies the template(html5 templates does not render on your screen) into another div. This allows you to reuse the DOM.
Problem: The line "span.textContent = parseInt(span.textContent) + 1;" changes the template code directly. I need to manipulate the content DOM and clone it into the container, without changing the template. This is very important since if I want to reuse the code, I need it to stay the same.
I have tried multiple ways to use jQuery to mimic the above javascript code, but I can't manage to figure it out. It would be better if there is a jQuery way.
If you NEED to use the new <template> tag, then you are mildly stuck . . . your cleanest alternative is to use importNode to bring in the content and then modify it after it's been appended.
Assuming that the templated code is realtively small, this should happen fast enough that you would never notice the difference in approach, though, in this specific example, the alert(), would delay the change of the content, so you would see "0", until you clicked "Okay", and then it would update to "1".
The code change for that would be:
function useIt() {
var content = document.querySelector('template').content;
var targetContainer = document.querySelector('#container');
targetContainer.appendChild(document.importNode(content, true));
var $span = $(targetContainer).find("div:last-of-type").find("span");
$span.text(parseInt($span.text() + 1));
}
If you are not married to the idea of <templates>, you could use jQuery's clone() method to do what you want to do, very easily . . . but, clone does not "see" the content of a <template>, due to the special nature of that particular element, so you would have to store the templated code some other way (JS variable, hidden div, etc.).
HOWEVER, this method will not work if you need to clone a script, the way that a <template> will. It will not trigger any script code in the "template container" element when the cloned version is created or appended. Additionally, if you store it in a hidden <div>, any script code in the "template container" element will trigger immediately on page load.
A simple version of the code for the clone() approach would look something like this:
function useIt() {
var $content = $("#template").clone();
var $span = $content.find("span");
$span.text(parseInt($span.text()) + 1);
$content.children().each(function() {
$("#container").append($(this));
});
}
Assuming that your template was:
<div id="template" style="display: none;">
<div>Template used: <span>0</span></div>
<script>alert('Thanks!')</script>
</div>
You could also move the <script>alert('Thanks!')</script> out of the template and into the script section (after you completed the "append loop"), to achive the desired alert functionality, if you wanted to.
It's an old question, but, did you try cloneNode(true)? It works on templates, as this:
var span = content.querySelector('span').cloneNode(true)
regards.
Is possible change color of background my div using JavaScript without using ID? And how?
Html code is:
<div class="post" onmouseover="test(this)">
JS code is:
function test(item){
alert("Hi :-)");
}
Have you tried
function test(item){
item.style.backgroundColor = "red";
}
Since item is the actual div you're triggering this event on you won't need an ID to style the element.
A really easy (inline) solution would be the one below.
<div class="post" onmouseover="javascript:style.backgroundColor = 'red';">
Content blabla
</div>
I would personally rather do all of this inside a JS file but hey this works too.
You can loop through the DOM with JavaScript, but you'll have a better time of it if you're using JQuery. You'll want to invest some time learning about selectors:
http://api.jquery.com/category/selectors/
http://www.w3schools.com/jquery/jquery_ref_selectors.asp.
You'll be looking for something like:
function test(){
var element = $('div');
}
As people have shared in the comments, without a unique identifier, you'll have a rough time, especially as new elements are added to the page.
attempting to have my webpage be a bit more dynamic by having the background change on some elements when a checkbox is clicked. I am trying to do this via class change and a CSS sheet. I have the following which is kicking out an error that my onclick function ins not defined (in IE9). More importantly will the webpage update if I only change the class of the object which would have a different class in the CSS file. Whats a better alternative if this does not work?
my elemenet and function
UPDATE
I made updates to both my HTML and CSS file as suggested by many. I am still getting no change in my webpage but the console is claiming that my function called from the onclick event is not defined which is a bit odd since it is. Also does this type for scripting belong in the HTML or should I pull it out and put in a seperate file. I figured since it was creating elements it belongs in the main html. Is there a cleaner more compact way of accomplishing this and not making my home screen html huge?
<tr class= 'tr.notchosen'><td><input type='checkbox' onclick='handleClick(this.id)'/></td></tr>
function handleClick(cb) {
var currentColumn = cb.parentNode
var currentRow = currentColumn.parentNode
if (currentRow.className === "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}
}
and my css file is the following
tr.chosen
{
background-color:rgba(255,223,0,0.75);
}
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
There are a couple of things going on here. First, your css selector is not quite right. In fact, I would suggest making the class name just "chosen" or "not chosen" and then selecting tr elements with that class.
<tr class='notchosen'>
And then you can target it from css (which was probably the original intention)
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
Further, although I would not suggest using inline javascript, using your example, you should pass this if you want to work with the element and not this.id which would pass a string.
onclick='handleClick(this)'
The last part would be to sync up your javascript with the class name change
if (currentRow.className == "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}
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.
This question already has answers here:
Overriding !important style
(11 answers)
Closed 1 year ago.
I tried to inject a style using this code:
document.body.style.color='green!important';
Per the CSS cascade ref, by applying the !important rule I can trump origin and specificity.
I tried to inject this using Firefox Firebug into www.google.com however no luck.
How do I inject a foreground color with an !important rule?
Per the spec, if you want to set the priority, not just the value, you have to use setProperty, like so:
document.body.style.setProperty ("color", "green", "important");
element.style.cssText = 'color:green !important';
should work for you.
style.cssText is the only way to add !important.
<script>
document.body.style.cssText='color: red !important;'
</script>
all answers are great but they all assumed the value of the attribute is fixed,, what if not
take look at my solution
this.style.setProperty("color", $(this).css('color'), "important");
instead of hand writing the value, I got it using jquery $(this).css('attr')
I would like to pose that it may not be working not so much due to any error in code (excepting the space) but more because modifying the body tag isn't a specific enough element, class, or what have you to create the desired effect.
Like for instance the page text of a search result has a class of "st".
all search results are each encapsulated in an
<li>
tag.
So some code to such effect might look like this:
var arr = document.getElementsByClassName('st');
for(i=0; i<arr.length; i++){
arr[i].style.color="green";
}
Use only this:
document.body.style.color="green";
you can not have to use important in this way. Anyway as Fatal pointed out, this will not work, when there is directly important rule in css stylesheet, that you need to override.
In that way, you have to dynamicaly create stylesheet and ad it inside head:
function addNewStyle(newStyle) {
var styleElement = document.getElementById('styles_js');
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = 'styles_js';
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
styleElement.appendChild(document.createTextNode(newStyle));
}
Then you can update style just like that
addNewStyle('body {color:green !important;}')
i need to keep !important for the following code how to do
<script> var size = $(window).width();
if(size >="1900" && size <="2890"){
$(document).ready(function(){ $(".myMove").click(function(){ $(".hqnblogo").animate({ left:'-22% ', top: '67%', height:'7%', }); $(".hqnbnaturalslogo").animate({ left: '86%', top: '20px', height:'7%', }); }); }); } </script>?