Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/CSS : Focus a paragraph

I want to focus each "p" tag separately when I click on it, like a CSS "focus:" on an input. The problem is that the selector "focus" doesn't work on paragraphs, here is an exemple :

HTML

<div id="myDiv">
    <p>Some Content 1</p>
    <p>Some Content 2</p>
    <p>Some Content 3</p>
    <p>Some Content 4</p>
</div> 

CSS

#myDiv p:focus {background-color:red;}

How can I find an alternative solution to make it work?

like image 336
Hiroyuki Nuri Avatar asked Sep 04 '15 14:09

Hiroyuki Nuri


People also ask

How do you focus a paragraph?

Focus sentences tie the paragraph to the title, the introductory paragraph and the main topic of the essay. In addition to introducing the paragraph's topic, they hint at the paragraph's supporting information as well as the paragraphs that follow.

Can I set focus with CSS?

No, there isn't. In normal circumstances, a div can't receive the focus at all, and CSS lacks anything to set the focus.


2 Answers

You can add tabindex to the p tag to achieve this

#myDiv p:focus {
    background-color:red;
}
<div id="myDiv">
    <p tabindex="0">Some Content 1</p>
    <p tabindex="0">Some Content 2</p>
    <p tabindex="0">Some Content 3</p>
    <p tabindex="0">Some Content 4</p>
</div>

Jquery solution will be

click = false;
$(document).click(function(e) {
  if(!($(e.target).is('p'))) {
    $('p').css('background', 'transparent')
  }
})
$('p').click(function() {
    $('p').css('background', 'transparent');
    $(this).css('background', 'red');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="myDiv">
  <p>Some Content 1</p>
  <p>Some Content 2</p>
  <p>Some Content 3</p>
  <p>Some Content 4</p>
</div>
like image 51
Akshay Avatar answered Oct 06 '22 04:10

Akshay


Here is a javascript only version:

function highlight(theP)
{
	var x = document.getElementsByTagName("p");
	var i;
	for (i = 0; i < x.length; i++)
	{
		x[i].style.background = "";
	}

	theP.style.backgroundColor = "red";
}
<div id="myDiv">
    <p onclick="highlight(this);">Some Content 1</p>
    <p onclick="highlight(this);">Some Content 2</p>
    <p onclick="highlight(this);">Some Content 3</p>
    <p onclick="highlight(this);">Some Content 4</p>
</div>
like image 40
Lance Avatar answered Oct 06 '22 04:10

Lance