Add replace the class of a div upon some conditions with Javascript - javascript

I am trying to replace the class of a div with Javascript. I have looked at some posts but it did not seem to help (e.g. Change an element's class with JavaScript). I have a straightforward innerHTML
document.getElementById("colored-title").innerHTML = "Add comments";
HTML is straightforward as well and it works when there is no condition on the class
<div id="colored-title"></div>
I tried many options (I listed them all below) but none of them seems to work.
if (array[current][5] == 4) {
document.getElementById("colored-title").addClass("green-text");
document.getElementById("colored-title").className= "green-text";
document.getElementById("colored-title").className+= "green-text";
document.getElementById("colored-title").setAttribute=("class","green-text");
} else {
// other format
}
document.getElementById("colored-title").innerHTML = "Add comments";

You can add classname throught javascript by .classname='classname'
This should work.check your if condition to see why it is not working
window.onload = function() {
document.getElementById("colored-title").className= "green-text";
}
.green-text {
color: green;
}
<div id="colored-title">
hello
</div>
Hope it helps

If you have jQuery in your project, then setAttribute should look like this:
$("#colored-title").attr("class", "green-text");
You have to use the jQuery selector, not document.getElementById.
Edit: Worth noting, the .attr method can also set multiple things at once:
$("#thing").attr({class:"green-text", title:"green-Object", id:"green-Id"});

This statement will add the correct class to your div:
document.getElementById("colored-title").className= "green-text";
But with the following statement you are changing the class from "green-text" to "green-textgreen-text":
document.getElementById("colored-title").className+= "green-text";

If you have jQuery in your project, then
$("#elem").addClass("myClass");
.myClass {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="elem">
Text
</div>

Related

Adding CSS to and added input elements using Javascript

I'm new to JavaScript. I managed to add dynamic inputs after clicking on a button but I want to know how to apply the CSS to those added inputs, if anyone can give me a simple example i'd be glad!
Thank you!
Perhaps something like this:
<button onclick="newInput()">Add new input</button>
function newInput() {
var newElement = document.createElement("input");
newElement.className = "newClass";
document.body.appendChild(newElement);
}
And in the style section, or in the .css file, you'll have:
.newClass {
/*Styles go here*/
display: block;
}
Fiddle example of the above: http://jsfiddle.net/8zen9wwo/3/
Here is a very simple example using jQuery:
http://jsfiddle.net/kmrvpz99/
Html Code
<div class="container"></div>
Javascript Code
$('.container').append('<input type="text" class="yourstyle">');
var manualCss = $('<input type="text">').css('background-color', '#333');
$('.container').append(manualCss);
The css File
.yourstyle {
background-color: #000;
}
By defining .yourstyle in the css file, all elements on the html site that possess this class, even those dynamically added via javascript, will use this style. You can however manually modify the css by setting the style attribute on the element directly.

Search page for class .has-error

So I have built some validation in Javascript and when a field has an error the div <div class="form-group">...</div> becomes <div class="form-group has-error">...</div>
I then have a .btn-bar div that contains the button for submitting the form. I have this hidden by default when the page loads:
$(document).ready(function(){
$('.registration-information').hide();
$('.btn-bar').hide();
});
I have a function to show the .btn-bar:
function enableButtons(){
if(noErrors){
$('.btn-bar').slideDown();
}
}
Now obviosuly, the script above doesn't work. More specifically, the if statement. My question, is how do I search for a div that has has-error in the class name on the page? If there is one then the btn-bar does not show, if there isn't any then the btn-bar shows.
It's actually fairly simple in jQuery. Try something like this:
function noErrors() {
return $('.has-error').length == 0;
}
function enableButtons(){
if(noErrors()){
$('.btn-bar').slideDown();
}
}
I separated noErrors() into its own function, in case there are other validation tests you eventually want to add in that aren't related just to the .has-error class.
Good luck!
You can achieve this simply by doing this :
$(document).ready(function(){
$('.registration-information').hide();
$('.btn-bar').hide();
if (!$('.has-error')) {
$('.btn-bar').slideDown();
}
});
It will check to see if any element has the class .has-error , and if it does not ! exist anywhere on the page, it will show the .btn-bar.

jQuery and selectors in use with specific span tags

jQuery selector
Selecting specific span tags
I had this problem with jQuery's selector. It was a problem for hours. It could not select that specific span tag that I wanted to manipulate and that's why I'm stuck scratching my head with this one.
My goal was to add different classes for each span tag that had different style values.
Thus I almost succeeded I couldn't figure out how to add different classes to each span tag, so I ended up clueless.
I basically want the span with font-size of 180% to be in a specific class doesn't matter which really cause I can change that later if the code works. The other span tag with font-size of 100% should also have a class, the other class. I hope you get more clarity in what I'm trying to do now at least that's what I'm hoping for.
The code exists in the link below, feel free to post a fix and optionally but not required a explaination of why it didn't work! thank you.
jQuery Submission: JS Bin Post
Here's the code itself aswell.
var val1 = "font-size: 180%";
var val2 = "font-size: 100%";
var title = $("span").attr("style");
$(function(){
if ($("span:contains('font-size: 100%')")) {
$('span').addClass("text_shadow2");
if ($('span').has("text_shadow1")) {
$('span').removeClass("text_shadow1");
}
}
if ($("span:contains('font-size: 180%')")) {
$('span').addClass("text_shadow1");
if ($('span').has("text_shadow2")) {
$('span').removeClass("text_shadow2");
}
}
},function(){
if ($("span:contains('font-size: 100%')")) {
$('span').addClass("text_shadow2");
if ($('span').has("text_shadow1")) {
$('span').removeClass("text_shadow1");
}
}
if ($("span:contains('font-size: 180%')")) {
$('span').addClass("text_shadow1");
if ($('span').has("text_shadow2")) {
$('span').removeClass("text_shadow2");
}
}
});
if ($(val1==title)) {alert("1. "+title);}
if ($(val2==title)) {alert("2. "+title);}
You could do something like this to parse the style attribute. Browsers aren't going to set the font-size property to a percentage but will do the calcs instead
$('span').filter(function(){
return $(this).attr('style').match('180%');
}).addClass('someClass');
Demo: http://jsfiddle.net/AbZBD/

Can't change background of div region using javascript?

This should be so simple, but I'm making heavy weather of it.
Div region set out as:
<div class="maincontent">
Stuff in my div
</div>
CSS for that div:
.maincontent{
height: 100%;
background-size: 100%;
margin-left:1%;
margin-right:1%;
font-size:16px;
}
Then I have:
onLoad=changeBackground();
But before that I have the function:
function changeBackground(){
document.getElementByAnything('maincontent').style.backgroundColor="yellow";
}
I know its making the call to the function because if I put an alert box in there that shows. But no matter what combination of getElementBy I can't make any changes to the background?
Please help as its driving me insane!
TIA
Have you tried giving your div an id and using document.getElementById('divId') instead? I think if you want to get the element by class you have to use jquery.
getElementById('maincontent')
and change your div to have an id="maincontent"
Try giving the element an id and doing document.getElementById and then do console.log in firebug or other developer tools and verify that you are actually getting a dom element back.
Once you have verified that you should then be able to switch the background color
You're trying to select the div using its class. This isn't quite as straightforward as getting it by id. Try this:
<div class="maincontent" id='mainContent'>
Stuff in my div
</div>
function changeBackground(){
document.getElementById('mainContent').style.backgroundColor="yellow";
}
You can see a working example here: JSFiddle
If you want to get the element using its class, I would recommend using Jquery or another library.
If you're using in line Javascript then use, instead:
onchange="changeBackground(this)"
And:
function changeBackground(elem){
elem.style.backgroundColor = "yellow";
}
Edited as I suddenly remembered you were discussing events based on div elements. As a div doesn't natively support the onchange event, I'd suggest amending your code to the following (though changing the event-type onmouseover to whatever event you find most appropriate):
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
};
JS Fiddle demo.
Also, to remove the events from in-line code, and to make the JavaScript more portable and less 'intrusive':
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
}
var maincontents = document.getElementsByClassName('maincontent');
for (var i=0,len=maincontents.length; i<len; i++){
maincontents[i].onmouseover = function(){
changeBackground(this);
}
}
JS Fiddle demo.
Bear in mind, though, that some browsers (such as Internet Explorer 8 and below) don't support getElementsByClassName().
I recommend using jQuery if you want to select a DOM by class name.
Put this code in your <head> part of your html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
and change your function to
function changeBackground() {
$(".maincontent").css("background-color","yellow");
}

Click to show more - maybe JS?

I am not sure what language or how to do this, but I am looking to have a word on a page, and when clicked, it will reveal more underneath. If it is clicked again, that stuff will hide away again? Any ideas?
Basically, you will need to manipulate the display CSS property of the element to be hidden/revealed:
<span id="showHide">Show</span>
<div id="foo" style="display:none">Here is some text</div>
<script>
document.getElementById("showHide").onclick = function() {
var theDiv = document.getElementById("foo");
if(theDiv.style.display == 'none') {
theDiv.style.display = 'block';
this.innerHTML = 'Hide';
} else {
theDiv.style.display = 'none';
this.innerHTML = 'Show';
}
}
</script>
I'd recommend javascript and using jQuery .show() & .hide() methods:
http://api.jquery.com/show/
http://api.jquery.com/hide/
http://www.learningjquery.com/2006/09/slicker-show-and-hide
you could do this with jQuery, here a ready to use example:
http://jsfiddle.net/8sDLg/
$(function() {$('div.more').hide()
$('a.showmemore').click(function(){
$(this).next('div').slideToggle()
})})
Put the stuff in a div with style display:none;. In the onClick handler of the word (can be link or a button), toggle the display style between '' (which means 'default') and 'none'
I created a demo for you here.
You could use jQuery for that and make your life easy:
Show/Hide
<div id="mydiv">Some content</div>
jQuery:
$(function(){
$('#link').click(function(){
$('#mydiv').slideToggle();
return false;
});
});
As can be seen, the slideToggle() does the trick there for you :)
Executive summary: use a framework plugin
Long version:
You could use javascript -- more likely in a combination with a javascript framework, like jQuery. This would involve adding a click handler to the word (actually a span tag around it) and having a way to retrieve the extra information to show as a tooltip -- there are plenty of plugins for this. Search for "jquery tooltip" here or using google: here's one example.
Alternatively, you could simply surround the word with the span tag and add a title attribute to the tag. Hovering over the word (actually the tag) would bring up the browser's default tooltip. This might be an easy way to get started with it -- in fact, this could be the start of the javascript solution. Using the tag for the click event and taking the data from the title attribute -- probably by storing the title in jQuery data on page load, then grabbing the text from the data on click so that you don't have a conflict with the browser's tool tip behavior. Many of the plugins operate this way.
Another elegant approach using pure HTML and CSS without JavaScript.
HTML:
here goes text before
<label class="details">
<input type="checkbox" /><span>here come some details</span><em> </em>
</label>
and after
CSS:
.details input,
.details span {
display: none;
}
.details input:checked~span {
display: inline;
border-bottom: dotted 1px gray;
}
.details em:after {
content: "show...";
}
.details input:checked~em:after {
content: "...hide";
}
Quick idea how to do it when avoiding a JS-only solution. I'm using jQuery here, because it is faster to code in, but as I mentioned above, if this is your only JS functionality it would only add a heavy-weight file for some trivial extras.
<script type="text/javascript">
jQuery(function() {
$(".article .additional")
.hide()
.before("<a href='#'>")
.prev()
.text("more")
.click(function() {
$(this).next().toggle()
})
});
</script>
<div class="article">
<h2>Some headline</h2>
<p>Some intro text that is always visible</p>
<div class="additional">
<p>Some extra text that is hidden by JS</p>
<p>But will stay visible if the visitor doesn't have JS</p>
</div>
</div>
As you see, the HTML is completely stand-alone. Only if JavaScript is supported, a "more" link will be added and the additional content hidden, so that non-JS users still can read all the text and don't have an useless "more" link.

Categories

Resources