javascript/css: change display property - javascript

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

Related

Display:flex does not load correctly on anchor tag?

I'm working on a full-stack project that is somehow loading inconsistent CSS styles on my anchor elements. Using Javascript I am doing something like the following:
recordData.forEach(record => {
let a = help.createElement('a');
let text = record.jobTitle + " (" + record.deptName + ", " + record.subDeptName + ")-" + record.email;
a.textContent = text;
a.href = `/frontend/contractorForm/contractorForm.html`;
a.addEventListener('click', function(event) {
sessionStorage.clear();
sessionStorage.setItem('record', JSON.stringify(record));
}, false);
parent.appendChild(a);
}
The idea of this was that although I have one single HTML form "template" created, I can populate the values inside contractorForm.html through values stored in my sessionStorage.
Below are my anchor tag frontend views and I also attached images of what happens when I click on other ones. The problem with this is that when I click on my anchor tags on the front end, this is what I get.
My CSS for contractorForm.html is basically display:flex; justify-content:center. But as shown in the images, only the first anchor link works.
Things I've checked and verified: CSS page does load when looking at Devtools, disabling and clearing cache, attaching ?version={random number} onto the .html href, changing style on devtools to see if it works (and it does), changing the background color (it works perfectly), loading my CSS code after bootstrap link, checking paths and links (all correct)
The only issue here is that my display: flex is simple just not working. Any help or ideas will be appreciated! Thank you!
anchortaghtmlview
first-anchortag-click-view
second-anchortag-click-view
Fixed it - if you have CSS issues, make sure you are referring correctly to the parent.
My CSS looked like this before:
#contractor-form-section {
width: 50rem;
}
#contractor-form is wrapping just the form element, and the way how my DOM structure looked like was something like this:
<body>
<div id="contractor-form-border">
<section id="contractor-form-section">
<h1>...</h1>
<form>
</form>
</section>
</div>
</body>
Essentially, my CSS was referring to #contractor-form-section rather than #contractor-form-border. Switching to that basically fixed the issue!

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.

Javascript styling toggle doesn't work first click

I'm making this little html app with a sidebar menu that pops up on click. It works fine except that it only starts to work after the second click. On the first click nothing happens.
CSS:
#menubalk{
margin-left: -260px;
}
HTML:
<div id="menubutton">
<img src="design/images/menu.png" id="menu" onclick="toggle()" alt=""/>
</div>
<div id="menubalk">
<h5>Menu</h5>
</div>
Javascript:
function toggle () {
var el = document.getElementById("menubalk");
var kop = document.getElementById("kop");
var pag = document.getElementById("pagina");
if ( el.style.marginLeft=="-260px" ) {
el.style.marginLeft="0px";
kop.style.marginLeft="260px";
pag.style.marginLeft="260px";
} else {
el.style.marginLeft="-260px";
kop.style.marginLeft="0px";
pag.style.marginLeft="0px";
}
}
I think I might have to set the margin somewhere in the javascript also but I can't figure it out.
All help is greatly appreciated!
style.marginLeft is looking at your inline styles. As you haven't defined any inline style initially style.marginLeft is undefined.
To fix this, you could simply reverse your if/else statement:
if ( el.style.marginLeft=="0px" )
element.style only search for inline style, to get actual style you can use getComputedStyle
i.e.
if ( window.getComputedStyle(el).marginLeft=="-260px" ) {...
Reference: https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle
Note: For IE, this only works for IE9 or above.
With this line
if(el.style.marginLeft=="-260px") {
You are checking if the inline style of the element is a specific value. However, this style is set in the css. I recommend adding a className to the menu to expand it. You can check for this classname and add/remove it accordingly:
if ( el.className == "expanded" ) {
el.className = "";
} else {
el.className = "expanded";
}
With this addition to the css:
#menubalk.expanded {
margin-left:0;
}
You say you set the menu style in the JavaScript somewhere but I would actually recommend doing that as part of your initialisation, rather than setting the left margin with CSS.
I suspect (it's hard to see without an example) that on the first click the JavaScript is going straight to the else condition because it's not recognising that you've set the margin in CSS (or elsewhere). Then on the second click, JavaScript has been used to set the left margin so it can read it and perform accordingly.

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");
}

Categories

Resources