I cannot understand when I get the console I get:
TypeError: boton is null
I've read about the error at the docs, but I still cannot understand why the button is null.
The desired action is click the button and if I have selected text, it will be pasted in the console.
I just get the error message.
These are the exact contents of my two files: index.html and the JS file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js.js" type="text/javascript"></script>
</head>
<body>
<style>
</style>
<button id="resaltador">Resaltar</button>
<div class="card" style="width: 35rem;">
<div class="card-body">
<h5 class="card-title" id="card-title">Card title</h5>
<h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
<p class="card-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lorem elit, porta eget imperdiet eu, aliquam in nisi. Vestibulum egestas finibus diam sit amet suscipit. Aenean faucibus eros magna, aliquam fermentum mi convallis non.</p>
</div>
</div>
</body>
</html>
function seleccionarTexto() {
//copy the selected text on a mouseup
var textoCopiado
document.addEventListener('mouseup', (e)=> {
if(window.getSelection().toString().length > 0) {
textoCopiado = window.getSelection().toString()
}
})
//if we click the button
var boton = document.getElementById('resaltador')
boton.addEventListener('click', (e)=> console.log(textoCopiado) )
}
seleccionarTexto()
You are calling your script before the boton element has finished loading, which causes the null value because the button doesn't exist yet.
You can just change <script src="js.js" type="text/javascript"></script>
to <script defer src="js.js" type="text/javascript"></script>
, adding the defer
attribute to tell the browser to defer execution until the page is finished loading.