Just starting out with JavaScript - updating the appearance of an element

Based on the value of a boolean, I am looking to control the visibility of specific tabs in my sidebar when the page loads.

var someVar = true;

function show_ifTrue() {
    if (Boolean(someVar) == true) {
        document.getElementById('x').style.display = 'block'; 
        console.log("I CHANGED IT");
    }
    else {
      document.getElementById('x').style.background = 'red';
    }
}
.sidebar {
    position: fixed;
    overflow-y: scroll;
    top: 0;
    bottom: 0;
    float: left;
    display: inline-block;
    z-index: 50;
}
#tab {
    display: block;
}
#x {
    display: none;
}
<div class="sidebar">
    <a href="#" id="tab"> Cats </a>
    <a href="#" id="x" onpageshow="show_ifTrue();"> Dogs</a>
</div>

I have exhausted various methods like adjusting the CSS for .sidebar a{...} and assigning individual display properties to each tab, using !important, modifying in JS via style.cssText or setting attribute, yet still struggling to update the display as desired.

Answer №1

To modify the color, the function must be called first. However, it seems that the function is not being called because onpageshow can only be added to the <body> element. You could move it there like this: <body onpageshow='...'>. Alternatively, if you prefer to work with just the div itself, you can use onload:

window.onload=function(){
    show_ifTrue();
}

You can also achieve this using onpageshow as follows:

window.onpageshow=function(){
    show_ifTrue();
}

Additionally, you don't need the Boolean prefix in your function, simply use someVar == true.

Answer №2

It seems like there was a missing closing bracket in the CSS for #tab (UPDATE: The OP has made changes to address this, but there may have been other issues as well). Additionally, using window.onload or onpageshow on the body element is recommended — it's the only element that will respond correctly. Once these adjustments are made, here's an example of a functioning code:

window.onload = function () {
    show_ifTrue();
}

var someVar = true;

function show_ifTrue() {
    if (someVar === true) {
        document.getElementById('x').style.display = 'block'; 
        console.log('CHANGE HAS BEEN MADE');
    }
    else {
        document.getElementById('x').style.background = 'red';
    }
}
.sidebar {
    position: fixed;
    overflow-y: scroll;
    top: 0;
    bottom: 0;
    float: left;
    display: inline-block;
    z-index: 50;
 }

#tab {
    display: block;
}

#x {
    display: none;
}
<div class="sidebar">
    <a href="#" id="tab"> Cats </a>
    <a href="#" id="x"> Dogs</a>
</div>

I trust this information proves useful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deleting a button from a list item or array in Angular 12

Having some trouble removing a list item with the click button, I've tried a few options but nothing seems to be working. Can anyone offer assistance? I need to remove a list item from my users array when clicked. Below is the Typescript code and cor ...

Updating the state of a React component through a button click using React-JS

In my React-JS project, I am using Semantic-ui to create form inputs and a submit button. These forms have a property called 'error', and the value of this property is determined by the state. The issue arises when I click on the 'Next&apos ...

Leverage the power of the React useFetch hook with an onclick/event

My component utilizes a custom reusable hook for making HTTP calls. Here is how I am using it: const { data, error, isLoading, executeFetch } = useHttp<IArticle[]>('news', []); Additionally, within the same component, there is a toggle che ...

Arranging an Array by Two Distinct Characteristics

I currently have an array that is grouped and sorted based on the "Program" attribute, which is working well. However, I now need to sort by a different attribute (Deliverable) within each group. Is this possible? If so, how can I achieve it? Below is an ...

Creating an Active Link in Bootstrap 5.0 (Beta 3) Navbar Using JavaScript

I am currently working with Bootstrap 5 (Beta 3 - no JQuery) on a static website, and I am facing the challenge of making a navbar link appear active. I prefer to achieve this using JavaScript instead of creating a separate navbar for each page. For instan ...

Creating stunning 3D animations using Canvas

I am knowledgeable about Canvas 2D context, but I would like to create a 3D animation similar to this example. Would using the Three.js library be the most suitable option for this type of animation? Any recommendations for tutorials or documentation tha ...

Using CSS with multiple background images and the "contain" property

Hey there! Is it possible to have multiple background images stacked on top of each other within a single div? I want the images to resize automatically with "background-size: contain;". Have you tried this before? background-image: url('../img/ima ...

How can I adjust the padding and width attributes of the mat-menu in Angular 5

Today, I am struggling with a piece of code. Whenever I click on the Details button, it is supposed to open a mat-menu. However, for some reason, I cannot seem to adjust the padding or width of the menu: <div id="box-upload" [hidden]="hiddenBoxUpload" ...

Is there a way to rotate the custom marker icon in vue2-google-map?

After reading the documentation, I discovered that using path is the only way to rotate the marker. In an attempt to customize my marker, I created my own PNG image. However, I have been unsuccessful in overriding the CSS of the marker. I even tried to ov ...

Constantly showing false values in AngularJS Firebase array objects

Encountering an issue with retrieving data from Firebase. When viewing console.log($scope.statusbaca), it shows 2 queries, true and false. However, in the app it only displays false. Apologies for any language barriers as English is not my first language. ...

In JavaScript, you can ensure that only either :after or :before is executed, but not both

My html slider is causing me some trouble <div class="range-handle" style="left: 188.276px;">100,000</div> Upon loading the page, I noticed that in Firebug it appears like this https://i.sstatic.net/Rgqvo.png On the actual page, it looks li ...

gulp-minify-css-names not altering any files during processing

For quite some time, I have been on the search for a solution that can assist me in automating the process of renaming/minifying class names in HTML, JS, CSS files simultaneously throughout my entire project using gulp. While there are many solutions avai ...

Updating text color in JavaFX for a textarea

I'm having trouble getting this to work. After checking the CSS analyzer in the scene builder, it seems that changing the text color in a textarea requires something like this: .text-area .text { -fx-fill: #1e88e5; -fx-font-size: 32px; } How ...

Ensure that all Woocommerce products have consistent height while allowing for variations in width

I am struggling with achieving consistent height for all the products on my website, while allowing for variable widths. I attempted to resolve this using UI, but unfortunately it was unsuccessful. Does anyone have suggestions on how to accomplish this u ...

How can you position the nav collapse toggle to the far right while still allowing it to collapse downwards on smaller devices with Bootstrap 5?

I am in need of a navigation section that is always visible on all devices, with a collapsible toggle aligned to the right. In Bootstrap 5.2, if I place the collapse toggle after the <div class="collapse navbar-collapse ..., the collapsible conten ...

What is the best way to ensure a consistent spacing between two flex items?

I am working on a project to enhance my knowledge by rebuilding Facebook. One of the new concepts I am learning is Flexbox. When you resize the login page of Facebook, you'll notice that the Navigation shrinks but the logo and login inputs remain sta ...

"Resolving the duplication issue of a textbox in Phonegap app

I encountered a strange issue recently. While trying to focus on the textbox in my PhoneGap application using touch, I noticed that there are actually 2 textboxes appearing. Please refer to the attached image: ...

Adding array elements to a JavaScript object

I find myself in a rather unique predicament that I'm struggling to navigate. I have come across some data structured as follows. Please bear with me if I use any incorrect terminology, as I am relatively new to this. usersByName: { "tester&q ...

React and Express failing to display content

After relocating my React frontend folder to my collaborator's Express backend folder, here is our updated file structure. https://i.stack.imgur.com/i77XJ.png This code snippet represents app.js which is responsible for rendering the website. const ...

Learn how to retrieve the current input value from a repeating form using Jquery

I have implemented a comment system with a delete option. Each comment has a POST form that posts a comment-id to delete.php. While this works in PHP, I am facing issues with it in jQuery. To delete a comment, the comment id needs to be passed to delete.p ...