1

I recently noticed that adding the :focus tag to the css of a div in a lwc does not seem to be applied. The :hover tag works just fine however so it seems to be specific to the :focus tag.

HTML

<div onclick={offerSelected} title={eligibleOffer.Type__c} class="focusEffect slds-box slds-box_x-small slds-grid slds-m-bottom_xx-small" key={eligibleOffer.Type__c} style="cursor: pointer;">
                        <div class="slds-col slds-large-size_2-of-12 slds-medium-size_3-of-12" >
                            <lightning-icon size="xx-small" icon-name="action:new" class="slds-m-left_small"></lightning-icon>
                        </div>
                        <div class="slds-col slds-large-size_10-of-12 slds-medium-size_9-of-12">
                            <p class="slds-text-heading_medium slds-m-left_x-small slds-text-align_left" style="margin-top:2px;">
                                {eligibleOffer.Type__c}
                            </p>
                        </div>
                    </div>

CSS

    .focusEffect:focus {
       background-color:red;
    }

However this works

    .focusEffect:hover {
       background-color:red;
    }
3

So, if you use chrome inspect, and force state of focus on the div, it will change color.

enter image description here

On your div, there is no indication saying that the element can be focused. You have to explcitly specify that it can be.

We use tabindex on div to specify that it can be focussed.

tabindex="0" means that the element should be focusable in sequential keyboard navigation, but its order is defined by the document's source order.

 <div class="focusEffect slds-box slds-box_x-small slds-grid slds-m-bottom_xx-small" style="cursor: pointer;" tabindex="0">
                        <div class="slds-col slds-large-size_2-of-12 slds-medium-size_3-of-12" >
                            <lightning-icon size="xx-small" icon-name="action:new" class="slds-m-left_small"></lightning-icon>
                        </div>
                        <div class="slds-col slds-large-size_10-of-12 slds-medium-size_9-of-12">
                            <p class="slds-text-heading_medium slds-m-left_x-small slds-text-align_left" style="margin-top:2px;">

                            </p>
                        </div>
                    </div>
0

you can add the tabindex attribute to the div to make it work

https://bitsofco.de/how-and-when-to-use-the-tabindex-attribute/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.