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?
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.
No, there isn't. In normal circumstances, a div can't receive the focus at all, and CSS lacks anything to set the focus.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With