Is there a way to activate the state of image buttons instead of just focusing on them in my existing code?

I'm new to programming and this is my first post here with just 3 days of experience. I need help making my default button active instead of just focused. I've tried looking at other posts, but I'm finding it hard to connect the dots because of my lack of experience.

The page I am working on is in squarespace so I want to keep it all in one code block. Currently, when users click anywhere else on the website, the buttons deactivate even if they click on blank areas.

Any advice you can provide would be greatly appreciated.

Answer №1

Welcome to the world of Stack Overflow.

One important thing to remember is that the :active pseudo element is only active when a user clicks (mouse-down) on something. Check it out here

The usual approach is to use the css class "active" and define a .active selector for styling any desired element.

In your current setup, the buttons are affected by hover and focus events, causing them to lose focus when clicked outside the button.

To address this issue, you can make some adjustments in both CSS and JavaScript. The modified sections are indicated by /* EDIT */

I do not recommend the last method where I rely on passing the element ID to the function and matching it with the button's class. A better practice would be to have the show function take the JavaScript event as an argument, use event.target to identify the clicked link, and then utilize getElementById based on attributes like data-target="more". This decouples the CSS class from the JavaScript implementation.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Services</title>
</head>

<style>/* Customize Button Size, Border, Background Color, and Alignment */

    .services {
        width:210px;
        height:135px;
        padding: 0px;
        border:0px;
        outline:0px;
        cursor: pointer;
        color: #999999;
        font-size: 20px;
        text-align: center;
background:   url("https://i.ibb.co/G5mn9nY/Services-Buttons-Combined-Big.png") no-repeat; /* Common background-image for all links */
    }

    
/* Set Button Text Styling for Mouseover and Active States */
/* EDIT */
    .services:focus, .services:hover, .services.active {
        color: black;
    }
    

/* Position Button Text*/
divtext {
    position: relative;
    top: 90px;
    }
    
/* Wrapper Div for formatting button areas */
.servicesbuttonwrapper {
    display: flex;
    flex-flow: row wrap;
    justify-content: space-around;
   }

/* Wrapper Div for arranging revealed description text */ 
.servicestextwrapper {
    text-align: left;
    margin-left: 100px;
    margin-right: 32px;
    top: 50px;
    position: relative;
}


/* Adjust Image rollover position based on Focus State */
    .assets      {
        background-position: 0 0;
    }
    
    /* EDIT */
    .assets:focus, .assets:hover, .assets.active  {
        background-position: 0 -135px;
    }
    
    
    .viz        {
        background-position: 0 -270px;
    }
    
    /* EDIT */
    .viz:focus, .viz:hover, .viz.active  {
        background-position: 0 -405px;
    }
        
    
    .software   {
        background-position: 0 -540px;
    }
    
    /* EDIT */
    .software:focus, .software:hover, .software.active  {
        background-position: 0 -675px;
    }
    
    .more       {
        background-position: 0 -810px;
    }
    
    /* EDIT */
    .more:focus, .more:hover, .more.active  {
        background-position: 0 -945px;
    }


/* Initially hide button descriptions */
#assets, #viz, #software, #more {
    display: none;
} 


</style>

<body>
   
<!--Wrapper div for positioning buttons using CSS-->
<div class="servicesbuttonwrapper">

<!--Base buttons with JavaScript functions for click behavior.--> 

    <a href="javascript:void(0)" id="defaultstate" onclick="show('software');" class="services software"><divtext>INTERACTIVE SOFTWARE</divtext></a>
           
   <a href="javascript:void(0)" onclick="show('assets');" class="services assets"><divtext>3D ASSET CREATION</divtext></a>
                
<a href="javascript:void(0)" onclick="show('viz');" class="services viz"><divtext>3D VISUALIZATION</divtext></a>
                
<a href="javascript:void(0)" onclick="show('more');" class="services more"><divtext>IMAGE CREATION</divtext></a>
   </div>
   
<!--Basic description text.--> 
   <div class="servicestextwrapper">
        <div id="assets">Description for 3D Assets.</div>
<div id="viz">Description for 3D Visualization.</div>
<div id="software">Description for Interactive Software.</div>
<div id="more">Description for Additional Services.</div>
   </div>   
   
<!--JavaScript function to show/hide elements upon button press.--> 
<script type="text/javascript">
    /* EDIT */
    function show(elementId) {
        document.getElementById("assets").style.display = "none";
        document.getElementById("viz").style.display = "none";
        document.getElementById("software").style.display = "none";
document.getElementById("more").style.display = "none";
        document.getElementById(elementId).style.display = "block";
        
        // get a list of buttons with ".services" class
        const buttons = document.querySelectorAll(".services");
        
        for(let button of buttons) {
          // remove ".active" class
          button.classList.remove("active");
        }
        
        // add the active class to the specified button element
        document.querySelector("." + elementId).classList.add("active");
    }  
   </script>
   
<!--JavaScript function to set the first button as focused.--> 
<script>
window.onload=function(){
  document.getElementById("defaultstate").click();
};
var linkToFocus = document.getElementById('defaultstate');
linkToFocus.focus();

</script>

</body>
</html>

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

Using Angular JS to manage multiple views with a single controller

Would it be considered best practice to use one controller, yet have two distinct HTML file templates that present the same data in different formats? Essentially, I require a slightly altered template for displaying content in a modal dialog and another ...

The NodeJS script is slowly consuming more and more memory

During my recent debugging session, I encountered a memory issue with a small to medium-sized Node.js app. Every time I utilize Chrome debug tools, the memory usage gradually increases by approximately 1mb every 15 minutes, even though I have not been able ...

What is the reason for npm and yarn to download multiple versions of jquery?

For the purpose of investigating how package managers like npm, yarn, and cnpm work in Node.js, I conducted an experiment. During the test, I came across two packages: jquery-dreamstream and jquery.tree. Both of them have a dependency solely on jquery wit ...

"Enhancing Grid Layouts with New Line Spacing in Bootstrap 4

I am currently utilizing the bootstrap 4 grid system. Within my grid, there are 3 columns, each containing a key value pair. This forms a nested grid structure. My concern arises when either the key or value exceeds one line, causing them to wrap onto a ...

Avoid refreshing AJAX on browser back navigation

Describing my current situation: I have a scenario with 2 pages: - On page 1, it sends a request using $.ajax to receive JSON data for display. Then there is a button that when clicked, takes me to page 2. - After clicking the button and transitionin ...

The usage of $http.post in combination with TypeScript accessors

Currently, I am developing an AngularJS application (v1.3.15) using TypeScript 1.5 in Visual Studio 2013. I have encountered a challenge related to TypeScript object properties and JSON serialization while utilizing $http.post(). Although I consider myself ...

What is the best way to show a dynamic number of data elements for a specific attribute in a Vue js component?

Currently, I am facing an issue with my Vue app where I have a product listing displayed using v-for. Each product has multiple headlines and corresponding top features. The layout for these headline-top feature pairs looks like this in the webpage: PRODU ...

Two fields placed horizontally next to each other, with their corresponding error messages displayed directly below in perfect

I have come up with a solution to my issue: http://codepen.io/helloworld/pen/QpRxNr?editors=1100 I am trying to display 2 inputs, each with an error message, in a table column. The current design is too elongated for my liking to fit in just ONE table c ...

How can I properly implement a Closure or IIFE to manage an onclick event in ReactJS?

I'm encountering an issue while attempting to utilize the this object in an event handler. An undefined error related to the this object keeps popping up. My development stack includes ReactJS and Redux as well. class Chat extends Component { c ...

Reading a glTF file from the local system onto Javascript's memory

Currently, I am working on developing a native iOS and Android application using three.js and Capacitor. One of the challenges I am facing is loading GLTF models from an asset folder that is bundled with the code and delivered to the user. I am unsure abou ...

There seems to be an issue with receiving the message sent through postMessage()

I seem to be encountering an issue with my syntax while attempting to pass a variable to an iframe (for colorbox integration). Currently, I've allowed all domains on both ends for testing purposes. Here is the JavaScript code for the sender page: $(d ...

Is it a bad idea to incorporate JavaScript functions into AngularJS directives?

I came across this snippet of code while working with ng-repeat: <div ng-show="parameter == 'MyTESTtext'">{{parameter}}</div> Here, parameter represents a string variable in the $scope... I started exploring if it was possible to c ...

Unable to submit AngularJS form - experiencing technical difficulties

I am encountering an issue with a form that takes input for the name of a country and should update a global variable. However, when the submit button is clicked, nothing happens. Can someone point out where I am going wrong? Below is the HTML code snippet ...

Compiling TypeScript to JavaScript with Intellij IDEA while preserving the folder hierarchy

Seeking assistance with maintaining directory structure when compiling Typescript to Javascript in Intellij Idea. The current directory setup is as follows: root - ts - SomeClass1.ts - SomeFolder - AwesomeClass2.ts - tsc The desired compiled file ...

Alert from Webpack regarding a critical dependency in the view.js file of the Express library located in the node_modules directory: an expression is being used

Currently, I'm in the process of working on my inaugural full stack application (a simplistic notepad app) and while bundling webpack, I've encountered an issue that is a cause for concern: WARNING in ./node_modules/express/lib/view.js 81:13-2 ...

Is there a way to modify a specific item within a useState Array in Reactjs?

Having a useState hook that stores data in the following structure: const [orderData, setOrderData] = useState({ demoData1: '', demoData2: '', demoData3: '', demoArrayData: [{itemName: '', itemNumber: ...

Flipping back and forth between two images within a single HTML file

I am looking to customize my top navbar for two different webpages, the root URL (/) and firstpage (/firstpage). The top navbar contains 2 images that I want to switch based on which page the user is currently on. Here is the code snippet: <img class=" ...

Align a link in the middle along with the header beside it

My HTML header currently has a simple title bar with a back href. However, the headline <h1> is positioned UNDER the href, which is not what I want. I am looking to create a centered title bar with a headline and a button that are aligned at the same ...

Tips for making WebDriver pause until Sencha AJAX request finishes

While testing a page with Selenium WebDriver, I encountered an issue related to the Sencha JavaScript library being used on the underlying page. The problem arises when I input a value into a field and an AJAX call is made to validate that field. If the va ...

Dealing with CORS policy challenge

I am encountering an issue with Access to XMLHttpRequest at 'http://demo.equalinfotech.com/Iadiva/images/product/1634623781ladiva_barbara_01.glb' from origin 'http://localhost:8100' being blocked by CORS policy due to the absence of the ...