Can't change background of div region using javascript? - 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");
}

Related

How to display a div/element on mouse hover using external JavaScript?

My divs are nested so i understand i cant display an element if its already hidden. I want the information(p1 inside my html code)to display once the mouse hovers over another element(h1 in my html. I have already made my paragraph 1 style to none in JavaScript, now i need it to re-appear, i have tried the following code to attempt to make it re-appear document.getElementById("1").onmouseover.style.display = "block"; but with no success.
This is My HTML code, ignore the order im new to web dev lol
This is the code i have tried but it doesnt seem to work
This is the end result i want, the circled text on hover display the paragraph
So a few things. For starters, put actual code into your questions instead of screen shots. If we can't reproduce your issue it's difficult to troubleshoot usually from just pictures.
Next, you might familiarize yourself with syntax a bit more since p1 isn't a valid HTML element.
Then, try not to rely on javascript too much and keep presentation stuff on the compositor thread. Here's an example accomplishing your goal with no javascript. Hope it helps, cheers!
p {
display: none;
}
h1:hover + p {
display: block;
}
<h1>Hover me</h1>
<p>PEEK A BOO!</p>
Yes, this is doable without javascript but since the question asked how to do it with, hopefully this helps get OP on the right track.
<div id="bioBlock" style="display:none">
<h2 id="1">
Cameron Lodge
</h2>
<p1 id="para">Im an avid learner of anything computers....</p1>
</div>
function showBioBlock() {
document.getElementById("bioBlock").style.display = "block";
}
https://jsfiddle.net/avL3j765/
document.getByElementId("myH1").onmouseover = function(){
displayH1("myP");
}
document.getByElementId("myH1").onmouseout = function(){
displayH1("myP");
}
function displayH1(myId){
if(document.getByElementId(myId).style.display == "block"){
document.getByElementId(myId).style.display = "none";
}else{
document.getByElementId(myId).style.display = "block";
}
}
This invokes a function that toggles the paragraph's style when the mouse enters and leaves the element. It assumes that you have an id on both your h1 and p tags, in my example myH1 and myP respectively.

Shrinking a Table in JavaScript

Never used JavaScript Before and I'm trying to fix this form in share point.
I want this text box to be small (like 1 row), until the user clicks it and then it should expand into a larger text box with like 10 rows. I apologize if this has been answered before, I don't even know what I should be looking for. Here is code I have that doesn't work, but does pop up an error message(I did not write this code):
alert(DescriptionID);
document.getElementById(DescriptionID).addEventListener("onmouseover", function(){
document.getElementById(DescriptionID).rows= "10";
});
document.getElementById(DescriptionID).addEventListener("onmouseout", function(){
document.getElementById(DescriptionID).rows= "1";
});
EDIT:
Here is what the current code will display:
EDIT2:
Thanks to a ton of help from you guys/gals I am close to finished! I can now understand it significantly better at least! Here is a picture of the code. The object is actually an "ms-formbody" ???
AND ANOTHER EDIT:
So here is the error i'm getting after using Johhny's code:
If you are using jQuery, this might work for you:
HTML:
<textarea id="expandingTextarea" rows="1">Enter Text</textarea>
JavaScript:
$(document).ready(function() {
$('#expandingTextarea').on('mouseover', function() {
$(this).attr('rows', '10');
});
$('#expandingTextarea').on('mouseout', function() {
$(this).attr('rows', '1');
});
});
I created an example here.
Update:
Using a click event to change/toggle to row count:
$(document).ready(function() {
$('#expandingTextarea').on('click', toggleExpand);
function toggleExpand() {
var oldRowCount = $(this).attr('rows');
var newRowCount = parseInt(oldRowCount) === 1 ? 10 : 1;
$(this).attr('rows', newRowCount);
}
});
Demo here.
In fact, you don't need JS to achieve what you want. CSS can do it for you.
<!--html-->
<textarea class="descr">This is description</textarea>
/*css*/
.descr {height: 20px;}
.descr:hover, .descr:focus {height: 120px;}
alter the height instead of the "rows" property.
open up the page in chrome, open the developer tools (View->Developer->Developer Tools) and then use "inspect" to select the text area you want to manipulate.
try playing around with the css of that element. then, write your javascript to change just the property that you want.
https://developer.chrome.com/devtools
The code you showed looks fine but DescriptionID should contain the ID of the description box. You can check what it is by right clicking on the description form and clicking "inspect element". Then assign var DescriptionID = "someID" at the beginning of the code.
Also, you might consider altering the height, not the rows.
If the form doesn't have an ID, look for an option to change the HTML and add one. If you don't have such an option, it's still possible to achieve what you want to do but you have to look beyond getElementById.

How to change the source of a child element with JavaScript?

I'm looking to change the source attribute of an image element when my parent element is clicked. The child/image element is actually nested within two div's which complicates things slightly and I have a suspicion this is where i'm going wrong in my code.
The JavaScript is as follows:
<script src="js/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function () {
$('.slideContent').hide();
$('.slideHeader').toggle(
function () {
$(this).next('.slideContent').slideDown();
$(this).children('.dropDownIcon').children('img').src = "./images/dropDownIconUp.png";
},
function () {
$(this).next('.slideContent').fadeOut();
$(this).children('.dropDownIcon').children('img').src = "./images/dropDownIconDown.png";
}
); // end toggle
}); // end ready
And the HTML is:
<div class="slideHeader">
<div class="dropDownIcon">
<img class="dropDownClass" src="./images/dropDownIconDown.png"/>
</div>
<div>
<p>2014</p>
</div>
</div>
<div class="slideContent">
<div>
<p>2014</p>
</div>
</div>
The slideDown and fadeOut functions from jQuery work fine. However the image change does not happen. So i'm confident my eror is within the following code:
$(this).children('.dropDownIcon').children('img').src = "./images/dropDownIconUp.png";
But as far as I can see, I select the correct elements in my chain. If anyone can shine any light on this it would be much appreciated. As everything else on the internet verifys the code above should work (Whilst a be little messy).
Thanks in advance.
src is an attribute of the img tag, so use .attr()
Try,
$(this).children('.dropDownIcon').children('img').attr('src', "./images/dropDownIconUp.png");
instead of using children selector twice use $(this).find('img').attr('src','./images/dropDownIconUp.png')
I know you have accepted the answer but let me tell you some points in brief
.src = "blah" would not work for jquery objects.$() always returns a jquery object and you must use .attr() or .prop() to work with jquery objects
However jquery provides a simple way to convert to javascript object
if you still want to use as a javascript object you could it this way
$(".slideHeader").children('.dropDownIcon').children('img')[0].src = "./images/dropDownIconDown.png";

javascript/css: change display property

I want to change display without documentGetElementById if possible but the following is not working.
html
Instructions<div id="showfaq1" style="display:none;">Open Box. Remove device. </div>
javascript:
function toggleFaq(faqid) {
//alert(faqid);
var divname = "showfaq"+faqid;
//alert(divname);
divname.style.display="block";
}
Can anyone tell me what I am doing wrong?
Thank you.
I can't get why you do not want to use getElementById, but...
If you have elements in order like this
Instructions
<div id="showfaq1" style="display:none;">Open Box. Remove device. </div>
Instructions
<div id="showfaq2" style="display:none;">Open Box. Remove device. </div>
...
Instructions
<div id="showfaqN" style="display:none;">Open Box. Remove device. </div>
You may use
Instructions
function toggleFaq(obj) {
obj.nextElementSibling.style.display = 'block';
}
In your code divname is a variable containing a string "showfaq1", which doesn't have style property.
To change the style of an element you need a reference to that element which you can obtain using document.getElementById(divname):
function toggleFaq(faqid) {
//alert(faqid);
var divname = "showfaq"+faqid;
//alert(divname);
document.getElementById(divname).style.display="block";
}
If you have an allergy to document.getElementById, you may use document.querySelector('[id="' + divname +'"]');, but its support is not as good as the former, and it's slower.
Posting a separate answer as it has no impact on my previous one. But you could make the base mechanism without JS at all, then use one of the JS-based solutions to fix it in broken browsers if needed:
HTML
Instructions
<div id="showfaq1">Open Box. Remove device. </div>
CSS
a + div { display:none; }
a:focus + div, a + div:target { display:block; }
DEMO

Override existing style declaration with jQuery

I have the following HTML code:
<style>
.thing { color: red }
</style>
<p class="thing">This is a nice thing</p>
I would like to change the ".thing"-style for all current content and all future content which comes to the page via AJAX.
$('.thing').css('color', 'blue');
This would work, but if new HTML code is added to the document via AJAX, all ".thing"-elements will still be colored red.
What I want is to change the whole style property ".thing" for the document and not only for the current elements (with a jQuery selector).
Thanks!
You could add a style rule in the header with the DOM
Demo: The Problem
Demo: DOM Mutation Solution
var newStyles = document.createElement("style");
newStyles.type="text/css";
newStyles.innerHTML = ".thing{color:blue}";
document.head.appendChild(newStyles);
You could use a call back function on your AJAX code to run the jquery css function.
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$('.thing').css('color', 'blue');
}
});
If for some reason you are not able to use any of the techniques given in the duplicate question, you could modify the stylesheet itself, for example:
document.styleSheets[1].cssRules[0].style.color = "blue";
However, the above line is not cross browser (I don't think it will work in IE, which prefers rules instead of cssRules) but it's possible to make it cross-browser compatible with a bit more code.
All it does is change the actual stylesheet, so it's like you had color: blue in there all along. This will affect elements currently on the page, and any that are added in the future (see the fiddle for a working example).
Note that you'll have to modify the indexes to suit your page. The indexes used in the example are just what work for the given stylesheet on jsfiddle.net.
Edit an attempt at a cross-browser solution:
var cssRules = (document.styleSheets[1].cssRules) ? document.styleSheets[1].cssRules[0] : document.styleSheets[1].rules[0];
cssRules.style.color = "blue";
You could add a style rule for blue text
<style>
.thing { color: red }
.thing.blue { color: blue }
</style>
and add "blue" class via call back function on your AJAX
$('.thing').addClass('blue');

Categories

Resources