How can you tell if a contenteditable div is currently in focus?

Essentially, my setup consists of:

HTML:

<div class="div1">
  <div class="as-text-box" contenteditable="true"></div>
</div>

CSS:

.div1{
  position:absolute;
  height:50px;
  width:200px;
  background:white;
  border:1px solid #ccc;
}
.as-text-box{
  position:absolute;
  height:30px;
  width:90%;
  background:#ddd;
  top:10px;
  left:5%;
}
[contentEditable=true]:focus .div1{
    border:1px solid black;
}

Specifically, I am looking to change the border color of div1 to black when as-text-box is focused.

I have also attempted to achieve this using JQuery but have not been successful.

JQuery:

$(function(){
    if ($(".as-text-box").is(":focus")) {
        alert("Has Focus");
    } else {
        alert("Doesn't Have Focus");
    }
});

Jsfiddle: https://jsfiddle.net/2xn5rj2y/

Any help and suggestions would be greatly appreciated.

Answer №1

To change the border of a parent element when a child element is focused using a CSS selector, you will need to use Javascript.

Here is an example of how to attach a listener to the blur and focus events of the editable div to achieve this effect:

$(".as-text-box").on("focus", function() {
    $(".div1").addClass("focusClass");
});

$(".as-text-box").on("blur", function() {
    $(".div1").removeClass("focusClass");
});
.div1{
  position:absolute;
  height:50px;
  width:200px;
  background:white;
  border:1px solid #ccc;
}
.as-text-box{
  position:absolute;
  height:30px;
  width:90%;
  background:#ddd;
  top:10px;
  left:5%;
}

.div1.focusClass {
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="div1">
  <div class="as-text-box" contenteditable="true"></div>
</div>

Answer №2

Your specific selector:

[contentEditable=true]:focus .div1

attempts to target a class called div1 within a contentEditable element that is in focus. However, this approach seems to be incorrect as the .div1 element is actually the parent of the contentEditable element.

By simply removing the .div1 part from the selector, the issue can be resolved:

.div1{
  position:absolute;
  height:50px;
  width:200px;
  background:white;
  border:1px solid #ccc;
}
.as-text-box{
  position:absolute;
  height:30px;
  width:90%;
  background:#ddd;
  top:10px;
  left:5%;
}
[contentEditable=true]:focus{
border:1px solid black;
  outline:none;
}
<div class="div1">
  <div class="as-text-box" contenteditable="true">
  
  </div>
</div>

Alternatively, if there are other reasons necessitating the selection on div1, reversing the order might also resolve the issue. However, the former solution appears to be the most straightforward unless there are additional requirements to consider.

Answer №3

If you're looking to customize the outline css attribute, you can use the following code:

CSS

outline:none;

For more information, you can visit this link.

Another option is to target the parent element and add a border using jQuery: .parent().css("border","1px solid #000");

Answer №4

It is impossible to achieve this using CSS alone (selecting the parent element), but you can accomplish it with jQuery using the focusin and focusout events to manipulate the parent element as needed.

$('.as-text-box').on('focusin', function(){
  /** when focused, add border to the parent element **/
  $(this).parent().css({'border':'1px solid black'});
}).on('focusout', function(){
  /** when focus is lost, remove the border **/
  $(this).parent().css({'border':''}); 
});
.div1{
  position:absolute;
  height:50px;
  width:200px;
  background:white;
  border:1px solid #ccc;
}
.as-text-box{
  position:absolute;
  height:30px;
  width:90%;
  background:#ddd;
  top:10px;
  left:5%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">
  <div class="as-text-box" contenteditable="true">
  </div>
</div>

Answer №5

This code provides a simple solution. The border of the element with focus will turn black, and once it loses focus, it reverts back to #ccc.

$('.as-text-box').on('focus', function() {
$('.div1').css("borderColor", "black");
$(this).on('focusout', function() {
    $('.div1').css("borderColor", "#ccc");
});

});

Check out the code in JSfiddle

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

Prevent Click Event in JQuery

I have a requirement to disable all click events on my webpage. However, even after using the appropriate code to prevent these events from firing, some of them are still getting called. Let me explain with an example. <div id='parent'> ...

Error: Invalid Argument - The argument 'PanelController' is expected to be a function, but it is undefined

Here is a snippet of my HTML code: <body ng-controller="StoreController as store"> ........... <section ng-controller="PanelController as panel"> <ul class="nav nav-pills""> <li ng-class="{active:panel.isSe ...

HighStock chart malfunctioning with inaccurate epoch datetime display

I am working on a project that involves creating a dynamic Highstock chart to showcase the daily influx of emails. The data is stored in a JSON file that gets updated every day, and you can see a snippet of it below: [{ "name": "Month", "data": [147199320 ...

Encountering a problem with the scope of child_process in Node

When utilizing the child_process module in Node.js with the fork method, I am able to send data to a specific file and receive a response. However, I am not logging this data to the console after receiving it from the execution process. The code in first. ...

Having trouble with JQuery toggle()? Need some assistance with fixing it?

My attempts to utilize JQuery toggle functionality have been unsuccessful. The sliding up and down animation is not smooth and instead happens very quickly. I aim to achieve a sliding effect in my code similar to this example (Please refer to Website Des ...

The video in the TypeScript code within the Owl Carousel is not displaying properly - only the sound is playing. The video screen remains stationary

I recently updated my query. I am facing an issue while trying to play a video in Owl Carousal with a button click. The video plays sporadically, and most of the time it doesn't work properly. When playing without the carousel, a single video works fi ...

iOS SDK - The Ultimate Tool to Unlock HTML 5 Player

Currently, I am facing a challenge while using Hpple to extract links from webpages. Due to the lack of support for Flash on iOS, I have to resort to the HTML 5 player. My objective is to locate and access this player. In scenarios where the website loads ...

Find the ID of the clicked table row using HTML and JavaScript

Currently, I am trying to implement this code snippet: <td align="center"> <div class="dropdown"> <button onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button> <div id="@TableR ...

Employing ng-show and other related features within directive "A"

After browsing through similar inquiries, I am still unable to comprehend the solution. If I have a directive available at this link: http://pastebin.com/QtAzGv62 and now need to incorporate the functionality of "ng-show" (or any other standard angular di ...

Ways to switch out error message for an error landing page

I am currently displaying error text when something goes wrong, but I would like to enhance the user experience by redirecting to a well-designed error page instead. Can anyone provide guidance on how to achieve this? Below is my existing code for display ...

Using jQuery to reveal or conceal content based on a particular class

Being a beginner in jquery, I have a question that might seem silly but I've searched everywhere for an answer without success. So, here it goes: I'm trying to display different content based on the option selected in a dropdown form. According ...

Issue with Node REST API: PUT request is failing to update data in the request

Encountering issues while attempting to update data through a PUT request. Despite making the request, the data remains unchanged and continues to display the previous information in Postman. Details of the PUT request sent via Postman: http://localhost: ...

Accessing an array within a function from a separate .JS file

Currently, I am facing a somewhat awkward predicament where I have a function in main.js that requires an array that is populated in second.js... In simple terms, the function in main.js is designed to be reusable: function chug() { p1.innerHTML = st ...

Jquery is causing some issues with the code provided:

This is the code snippet from script.js: $(document).ready(function() { $('#mainobject').fadeOut('slow'); }); Here is a glimpse of index.html: <!DOCTYPE html> <html> <head> <title>Hitler Map&l ...

Exploring the concept of multi-level mapping within Next.js

I'm currently facing an issue while trying to map over an object and display the desired result. The first mapping is working fine, but I am encountering problems with the second map inside the <ul> element. const data = [ { ti ...

Importing JSON data from a URL to display in an HTML table

Looking to utilize the Untappd API for a beer menu project, I've encountered an issue. The goal is to showcase the JSON data received from the server and organize it into an HTML table. Despite successfully importing data from a local list.json file ...

Automatically populate fields when the selection changes

Currently, I am facing an issue with a mysql table named clients that I utilize to populate the options of a select in one of the rows. The goal is to automatically fill out 2 input fields with client information when a specific option is selected. To acc ...

Having trouble with the mouse trail code on codepen.io

I am currently attempting to integrate this specific CodePen sample into a Hugo template called Somrat Theme. I'm facing challenges in deciding where to place the HTML file; only the 'no cursor' section should go into style.css, and I need ...

I am encountering difficulties while attempting to generate the chart series in Highcharts

This is just a demonstration https://jsfiddle.net/kkulig/0k4m5d2q/ I have made some changes to the original code Swapped out the following var originalCategories = [new Category('A'), new Category('B'), new Category('C')].m ...

Transforming a curl command into a jQuery $.ajax() call using JavaScript

I am currently facing an issue while trying to make an API call using jQuery AJAX. Even though I have successfully implemented it using curl for the API, my AJAX request is resulting in an HTTP 400 error. The command provided on the official API website is ...