Jump to content
vmars316

How to tell which <p> 'id=' has focus ?

Recommended Posts

How to tell which <p> 'id=' has focus ?
Hello & Thanks ,
The problem with  'document.activeElement.tagname' is that
for p element it returns 'BODY' .
But I want to know which p has focus .
Pls, How can this be done ?
Here is the prototype function I was working on .

<!DOCTYPE html>
<html>
<title>Which Element Has Focus</title>
<!--
-->
<body onload="documentURL()" onclick="myFunction()" >

<p>Click anywhere in the document to display the active element.</p>
<input type="text" value="An input field">
<button>A Button</button>

    <p id="demo">Who dunnit ?</p>
    <br>
    <p id="currentPage_Address" style="fontsize: 12px; color: #34495E;">Current Page Address</p>
<script>
function myFunction() {
  var x = document.activeElement.tagName;
  document.getElementById("demo").innerHTML = x;
}
</script>
      <script>
         var  p_tgh = "";
         var  pp_tgh = "";
         var  p_tghCount = 1;
         var  p_ah = "";
         var  pp_ah = "";
         var  p_ahCount = 1;
         var  ArticleHeading = "Heading";
         var  TextParagraph = "Text Paragraph";
         var  ButtonParagraph = "New Link";
         var  document_URL;
         const  filename = "myStory.html";
         var allHtml =  document.documentElement.outerHTML; 
         var  document_URL;
         function documentURL() {
         document_URL = document.URL;
         document.getElementById("currentPage_Address").innerHTML = document_URL;  
//         window.addEventListener("keydown", onPress_ENTER, false);
         }
      </script>

</body>
</html>

And I would like to put some working code in here:
    'function onPress_ENTER(event)'
Triggered by this:
    'window.addEventListener("keydown", onPress_ENTER'
Here is the full code where I want to put "WhichParaHasFocus".

<!DOCTYPE  html>  
<html>
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>MyStory.html</title>
      <!--   
         file:///C:/Users/vmars/Desktop/myPrograms/HeyBuddy/~~Hey-Buddy-WIP/MyStory.html
         https://www.dummies.com/web-design-development/css3/using-the-div-tag-to-create-tables/
         https://www.freeformatter.com/html-validator.html 
         <a href="https://developer.mozilla.org/en-US/" target="_blank">
         <img src="https://mdn.mozillademos.org/files/6851/mdn_logo.png"alt="MDN logo" />
         </a>
         still to do: intercept 'enter-key' replace with 8 spaces ELSE just cancel it .
         -->  
      <style type="text/css">
         body {
         font-family: Comic Sans MS;
         height: 100%;
         margin: 0 auto;
         padding:0;
         }
         html {
         height: 100%; 
         margin: 0 auto;
         padding:0;
         border: 0;
         }
         .Table {/*  wrapper  */
         min-height:100%;
         text-align: center;    
         margin: 0 auto;
         padding:0;
         }
         #mainHeading {
         color: #566573 ; 
         text-align: center;
         width: 100%;
         background: #BCCE98;
         vertical-align: top;
         margin: 0 auto;
         padding:0;
         }
         #container {
         padding-bottom: 1001em;
         margin-bottom: -1000em;
         overflow: hidden;
         margin: 0 auto;
         padding:0;
         }
         #Row1
         {
         display: block;
         width: 100%;
         vertical-align: top;
         margin: 0 auto;
         padding:0;
         }
         #Row2
         {
         display: block;    
         width: 100%;
         margin: 0 auto;
         padding:0;
         }
         #Row3
         {
         width: 100%;    
         margin: 0 auto;
         padding:0;
         display: inline;   
         }
         #Row1Cell1
         {
         color: #4C4C4C; 
         display: inline-block;   
         text-align: center;
         width: 100%;
         font-size: 18px
         }
         #Row2Cell1
         {
         display: inline-block;   
         background-color: #DAE9BC;
         width: 20%;
         margin: 0 auto;        
         float: left;
         padding-bottom: 1001em;
         margin-bottom: -1000em;
         }
         #Row2Cell2
         {
         display: inline-block;   
         text-align: left;
         width: 60%;
         background-color:#F8F8FF;
         margin: 0 auto;         
         float:left; 
         padding-bottom: 1001em;
         margin-bottom: -1000em;
         }
         #Row2Cell3
         {
         display: inline-block;   
         width: 20%;
         background: #e9f2d7; 
         margin: 0 auto;         
         float: right;
         padding-bottom: 1001em;
         margin-bottom: -1000em;
         }
         #Row3Cell1
         {
         display: inline-block;   
         width: 100%;
         background: #BCCE98;
         margin: 0 auto;    
         overflow: auto;      
         text-align: center;         
         }
         div{ 
         text-align: left;
         font-size: 14px
         }
         .p_bn {
         text-align: left;
         }
         .p_ah {
         color: DarkGreen;
         text-align: left;
         font-size: 16px
         }
         .p_tgh {
         color: #566573; 
         text-align: left;
         font-size: 14px
         }
         #left_note {
         color:#5886BC;
         }
         #left_note {
         color:#576C15;
         }
         #currentPage_Address {
         color:#e9f2d7;
         }
      </style>
   </head>
   <body onload="documentURL()">
      <!-- Run me 1st -->
      <div class="Table">
         <!-- ============NewRow============== -->
         <div id="Row1">
            <div id="Row1Cell1">
               <p contenteditable="true" id="mainHeading">MainHeading</p>
            </div>
            <!-- <div class="Cell"  -->
         </div>
         <!-- <div class="Row"  -->
         <!-- ============NewRow============== -->
         <div id="container">
            <div id="Row2">
               <div id="Row2Cell1">
                  <p contenteditable="" class="left_note" style="color:#5886BC;">notes</p>
               </div>
               <!-- <div class="Cell"  -->
               <div id="Row2Cell2">
                  <p contenteditable="" class="p_ah">Heading</p>
                  <p contenteditable="" class="p_tgh">Text</p>
               </div>
               <!-- <div class="Cell"  -->
               <div id="Row2Cell3">
                  <p contenteditable="true" class="right_note" style="color:#576C15">notes</p>
               </div>
               <!-- <div class="Cell"  -->
            </div>
            <!-- <div class="Row"  -->
         </div>
         <!--  id="container"  -->
         <!-- ============NewRow============== -->
         <div id="Row3">
            <div id="Row3Cell1">
               <br>
               <button onclick="createLeftNote()">Add Left Note</button>
               <button onclick="createArticleHeading()">Add Heading</button>
               <button onclick="createTextArea()">Add Text Paragraph</button>
               <button onclick="createRightNote()">Add Right Note</button>
               <form action="http://google.com" target="_blank" style="display: inline;">
                  <input type="submit" value="Search Google" />
               </form>
               <button onclick="saveAs(filename, allHtml)">Save This Page</button>
               <p id="currentPage_Address" > </p>
            </div>  <!-- id="Row3Cell1"  -->
         </div>  <!-- <div class="Row"  -->
      </div>  <!--  <div class="Table">  -->
      <script>
         var  LeftNote = "LeftNote";
         var  ArticleHeading = "Heading";
         var  TextParagraph = "Text";
         var  RightNote = "RightNote";
         var  ButtonParagraph = "New Link";
         var  document_URL;
         var  filename = "myStory.html";
         var allHtml =  document.documentElement.outerHTML; 
         var  document_URL;
         function documentURL() {
         document_URL = document.URL;
         document.getElementById("currentPage_Address").innerHTML = document_URL;  
         window.addEventListener("keydown", onPress_ENTER, false);

         }
      </script>
      <script>
      function onPress_ENTER(event){
        var keyPressed = event.keyCode || event.which;
        //if ENTER is pressed
        if(keyPressed==13)
        {
//            alert('enter pressed');
            event.preventDefault();
            stopImmediatePropagation();
        }
        else
        {
            return false;
        }
} 
      </script>
      <script contenteditable="">
         function createTextArea() {
                   var p_tgh = document.createElement("p");
                   p_tgh.innerHTML = TextParagraph;
                   p_tgh.setAttribute("contenteditable", "true");
                   p_tgh.setAttribute("class","p_tgh");
                   var content = document.getElementById("Row2Cell2");
                   content.appendChild(p_tgh);
                 }	
      </script>	
      <script contenteditable="">
         function createArticleHeading() {
           var p_ah = document.createElement('p');
           p_ah.innerHTML = ArticleHeading;
           p_ah.setAttribute('contenteditable', 'true');
           p_ah.setAttribute("class","p_ah");
           var content = document.getElementById('Row2Cell2');
           content.appendChild(p_ah);
         }
      </script> 
      <script>
         function saveAs(filename, allHtml) {
           allHtml =  document.documentElement.outerHTML; 
          var blob = new Blob([allHtml], {type: 'text/csv'});
          if(window.navigator.msSaveOrOpenBlob) {
              window.navigator.msSaveBlob(blob, filename);
          }
          else{
              var elem = window.document.createElement('a');
              elem.href = window.URL.createObjectURL(blob);
              elem.download = filename;        
              document.body.appendChild(elem);
              elem.click();        
              document.body.removeChild(elem);
          }
         }    
          
      </script> 
      <script contenteditable=""> 
         function createNewButton() {
           var p_bn = document.createElement("li");
           p_bn.innerHTML = ButtonParagraph;
           p_bn.setAttribute('contenteditable', 'true');
           p_bn.setAttribute("id","li-Default");
           var content = document.getElementById("nav-01");
           content.appendChild(p_bn);
         }
      </script> 
   </body>
</html>

Thanks

Share this post


Link to post
Share on other sites

If you want a paragraph to be focusable, you'll have to give it a tabindex attribute with a non-negative value.

  • Like 1

Share this post


Link to post
Share on other sites

Thanks Ingolme

I checked it out , but I don't want to dabble with tabindex .

I came up with a workaround that works for me:

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <!--  https://www.freeformatter.com/html-validator.html  -->
      <title>How to do lots of stuff:</title>
      <style type="text/css">
      </style>
   </head>
   <!--  -->
   <!-- body onload="documentURL()" .  -->
   <!-- Get & Display Current page's address .  -->
   <body onload="documentURL()">
      <!--  -->
      <p  contenteditable="" id="currentPage_Address" style="font-size: 8px; color: #34495E;" onclick='{has_Focus = "currentPage_Address"; whohasFocus();};'> </p>
      <p contenteditable="" style="color: darkgreen;" id="examplesIntro" onclick='{has_Focus = "examplesIntro"; whohasFocus();};'>
         These examples (work in progress) demonstrate 'How to': 
         <br>
         <br>body onload="documentURL()" .
         <br>Get & Display Current page's address .
         <br>Make a paragraph contentEditable .
         <br>Change Paragraph content innerHTML (press Enter_Key) .
      </p>
      <!-- Make a paragraph contentEditable .  -->
      <br>
      <p contenteditable="" id="p_tgh1" onclick='{has_Focus = "p_tgh1"; whohasFocus();};'>This is Paragraph id= p_tgh1</p>
      <p contenteditable="" id="p_ah1" onclick='{has_Focus = "p_ah1"; whohasFocus();};'>This is Paragraph id= p_ah1</p>
      <br>
      <p style="color: darkgreen;" id="showMe" onclick='{has_Focus = "showMe"};'>Show'em Who has Focus ?</p>
      <script>
         var  someDots = "....";
         var origContents = ".";
         var newContents = ".";
         var  document_URL;
         var  has_Focus = "none-yet";
         var allHtml =  document.documentElement.outerHTML; 
         var  document_URL;
         function documentURL() {
         document_URL = document.URL;
         document.getElementById("currentPage_Address").innerHTML = document_URL;  
         window.addEventListener("keydown", checkForEnterKeyDown, false);
         }
      </script>
      <script>
         function whohasFocus() {
           var focusPocus = ".";
           
           console.log("49 has_Focus= " + has_Focus);
           
//           document.getElementById(showMe).innerHTML = "."; 
           focusPocus = has_Focus + "  has focus.";

           console.log("54 has_Focus= " + has_Focus);

           document.getElementById("showMe").innerHTML = "Paragraph&nbsp; &nbsp;" + has_Focus + "&nbsp; &nbsp;Has Focus"; 
      }
      </script>
      <script>
         function checkForEnterKeyDown(event){
           var keyPressed = event.keyCode || event.which;
           if(keyPressed==13)
           { 
         // Change Paragraph content (innerHTML) .
         
           console.log("66 has_Focus= " + has_Focus);
           
           origContents = document.getElementById(has_Focus).innerHTML ; 
           newContents = origContents + someDots; 
           document.getElementById(has_Focus).innerHTML = newContents; 
         // Cancel onEnterKeyDown .
           event.preventDefault();
           event.stopImmediatePropagation();
           }
           else
           {
               return false;
           }
         } 
      </script> 
   </body>
</html>

Thanks

Share this post


Link to post
Share on other sites

Hmm...

This is pretty cool too (double whamy): 

<p contenteditable="" id="p_ah1" onfocus="{has_Focus = 'p_ah1'}; console.log(has_Focus); " onclick="{has_Focus = 'p_ah1'}">Heading</p>

 

Share this post


Link to post
Share on other sites

Might want to consider location.hash, you can retrieve what was clicked and use css to highlight it!

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0,user-scalable=no" />
        <title>Document Title</title>
        <script>
            function dothis(elem){
             location.hash = elem.id;   
             document.getElementById("demo").innerHTML=location.hash;   
            }
        </script>
        <style>
:target {color: red;}
</style>

    </head>
    <body>
        <div id="demo">Nout clicked yet!</div>
        <div>
            <p id="idRef1" onclick="dothis(this)">
                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </p>
            <p id="idRef2" onclick="dothis(this)">
                Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst.
            </p>
            <p id="idRef3" onclick="dothis(this)">
                Fusce convallis, mauris imperdiet gravida bibendum, nisl turpis suscipit mauris, sed placerat ipsum urna sed risus. In convallis tellus a mauris. Curabitur non elit ut libero tristique sodales. Mauris a lacus. Donec mattis semper leo. In hac habitasse platea dictumst. Vivamus facilisis diam at odio. Mauris dictum, nisi eget consequat elementum, lacus ligula molestie metus, non feugiat orci magna ac sem. Donec turpis. Donec vitae metus. Morbi tristique neque eu mauris. Quisque gravida ipsum non sapien. Proin turpis lacus, scelerisque vitae, elementum at, lobortis ac, quam. Aliquam dictum eleifend risus. In hac habitasse platea dictumst. Etiam sit amet diam. Suspendisse odio. Suspendisse nunc. In semper bibendum libero.
            </p>
            <p id="idRef4" onclick="dothis(this)">
                Proin nonummy, lacus eget pulvinar lacinia, pede felis dignissim leo, vitae tristique magna lacus sit amet eros. Nullam ornare. Praesent odio ligula, dapibus sed, tincidunt eget, dictum ac, nibh. Nam quis lacus. Nunc eleifend molestie velit. Morbi lobortis quam eu velit. Donec euismod vestibulum massa. Donec non lectus. Aliquam commodo lacus sit amet nulla. Cras dignissim elit et augue. Nullam non diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In hac habitasse platea dictumst. Aenean vestibulum. Sed lobortis elit quis lectus. Nunc sed lacus at augue bibendum dapibus.
            </p>
            <p id="idRef5" onclick="dothis(this)">
                Aliquam vehicula sem ut pede. Cras purus lectus, egestas eu, vehicula at, imperdiet sed, nibh. Morbi consectetuer luctus felis. Donec vitae nisi. Aliquam tincidunt feugiat elit. Duis sed elit ut turpis ullamcorper feugiat. Praesent pretium, mauris sed fermentum hendrerit, nulla lorem iaculis magna, pulvinar scelerisque urna tellus a justo. Suspendisse pulvinar massa in metus. Duis quis quam. Proin justo. Curabitur ac sapien. Nam erat. Praesent ut quam.
            </p>
            
            
        </div>
    </body>
</html>

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...