How to use event.target.matches to match div element - javascript

<!DOCTYPE html>
<html>
<head>
<style>
.dropdown-content a{
display: block;
background-color: blue;
}
</style>
</head>
<body>
<div class="dropdown-content">
<a>1</a>
<a>2</a>
</div>
<script>
window.onclick = function(event){
if(!event.target.matches('.dropdown-content')){
alert("foo");
}
};
</script>
</body>
</html>
I'm trying to make alert(foo); execute only when we are NOT clicking on anything inside of the div tag in the body. Unfortunately, it executes no matter where I click. Why?

window.onclick = function(event){
if (document.getElementsByClassName('dropdown-content')[0].contains(event.target)){
// inside
} else{
// outside
alert('foo');
}
};
.dropdown-content a{
display: block;
background-color: blue;
}
<div class="dropdown-content">
<a>1</a>
<a>2</a>
</div>
Get your element and use contains to check whether click is in or outside. If outside then alert.
matches is not working because you are clicking in a tag which is not having .dropdown-content tag. So everytime value comes false. And it alert('foo')

As i seen you have to add content to de div.conta, i made a demo
And work with the dom, className( imade right, but can use any):
<div class="dropdown-content">
abc
<a class="name">1</a>
<a>2</a>
</div>
window.onclick = function(event){
console.log(event.target.className);
if(event.target.className!=='dropdown-content'){
console.log("foo");
}
};

If you're using jQuery you can do the following:
$(event.target).closest('.dropdown-content').length
See the following JSFiddle:
https://jsfiddle.net/4nb691a0/

Because your if statement returns false and with ! operator returns true. It happens because when you clicked inside the div your actual target is <a> element which does not have class .dropdown-content.
When click outside the div it also does not have class .dropdown-content. So your statement always returns false but with ! operator it becomes true.
Try this:
<!DOCTYPE html>
<html>
<head>
<style>
.dropdown-content a{
display: block;
background-color: blue;
}
</style>
</head>
<body>
<div class="dropdown-content">
<a class="link">1</a>
<a class="link">2</a>
</div>
<script>
window.onclick = function(event){
if(!event.target.matches('.link')){
alert("foo");
}
};
</script>
</body>
</html>

Related

Easy way to set active class with javascript

I tried to find the easiest way to set the active class to the active Navbar point.
My Code looks like this:
function setActive(i) {
$(document).ready.getElementById(i).addClass("active");
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="../js/main.js"></script>
<script>
setActive("contact");
</script>
</head>
<body>
<a id="contact" class="nav-link" href="">Example</a>
</body>
Why is this not working?
Thanks for the help!
In jQuery, you use $().addClass(). You should call the function inside $(document).ready(), not have the function run only if the document has loaded.
In your setActive function, it looks like you are mixing up Javascript and jQuery. You should only use one or the other.
$(document).ready.getElementById(i).addClass("active");//this line is a syntax error
.active{
color: green;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function setActive(i) {
$('#'+i).addClass("active");
}
$(document).ready(function(){
setActive("contact");
});
</script>
</head>
<body>
<a id="contact" class="nav-link" href="">Example</a>
</body>
With pure Javascript, you can use Element.classList.add() to add a class to an element.
.active{
color: green;
}
<head>
<script>
function setActive(i) {
document.getElementById(i).classList.add("active");
}
document.addEventListener("DOMContentLoaded", function(){
setActive("contact");
});
</script>
</head>
<body>
<a id="contact" class="nav-link" href="">Example</a>
</body>
To set the contact active you need to this it this way. You already have jQuery in you code so it is more easy.
function setActive(tag){
//This bloc is optinal. It will remove active class from all other elements. You may not need that
$('body a').removeClass('active');
//End optional block
$(`#${tag}`).addClass('active');
}
$(document).ready(function(){
setActive('contact')
});
please try:
function addActive(el){
document.querySelector(el).classList.add("active");
}
You should call setActive("content") inside main.js inside a ready function
You are also missing the id selector (#) in your jQuery selector
$( document ).ready(function() {
setActive("contact");
});
function setActive(id){
$(`#${id}`).addClass("active");
}
.active{
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="contact" class="nav-link" href="">Example</a>
Try this
function setActive(i) {
document.getElementById(i).classList.add("active");
}
function setDisable(i) {
document.getElementById(i).classList.remove("active");
}
.active{
background-color: yellow;
color: red;
}
<html>
<body>
<button type="button" onclick="setActive('demo')">
Activate
</button>
<button type="button" onclick="setDisable('demo')">
Disable
</button>
<p id="demo">Here</p>
</body>
</html>

jQuery mouseup event on click and drag

I'm trying to show a div when the user click a box. I tried to use this code:
$(document).ready(function(){
$(".hold").mousedown(function(){
$(".box").css("height","200px");
});
$(".hold").mouseup(function(){
$(".box").css("height","0px");
});
});
But the second part of the code, the mouseup event doesn't trigger the callback when I click and drag.
How to make it work?
<!DOCTYPE html>
<html>
<head>
<title>click and hold project</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="hold"></div>
<div class="box"></div>
<script src="jquery-2.2.3.min.js"></script>
<script src="app.js"></script>
</body>
</html>
As #wahwahwah pointed it out, the issue is that when you press the mouse key on the .hold element and then move the mouse somewhere else and leave the key, the given handler on mouseup would NOT be called because it is set on the .hold element.
Technically, the target of the event would be different in that case, hence it won't match the .hold element and eventually the callback functions of mouseup event won't be triggered.
A workaround to this could be to add a pointer to the clicked element at the beginning and then add an event listener on the document element and check whether the event.target is the same as the clicked element.
If they are not the same, we will trigger the .hold element's event manually, as follows:
$(document).ready(function(){
var mouseTarget;
$(".hold").on('mousedown', function(){
$(".box").css("height", "200px");
mouseTarget = this;
})
.on('mouseup', function(){
$('.box').css("height", "0px");
});
$(document).on('mouseup', function(e) {
if (e.target !== mouseTarget) {
$(mouseTarget).trigger(e.type);
}
});
});
.hold{
background-color: #000;
width: 20%;
height: 10px;
}
.box{
background-color: #f00;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hold"></div>
<div class="box"></div>
It is worth mentioning that the callback function which is set on the document will be triggered in the bubble phase.
try the following
$(document).ready(function(){
$(".hold").mousedown(function(){
$(".box").css("height","200px");
})
.mouseup(function(){
$(".box").css("height","0px");
});
});
jsfiddle link https://jsfiddle.net/w47anse9/
Your code works as it is. Are you trying to drag or expand the box? I only added styles to it.
.hold {
width: 50px;
height: 50px;
background-color: yellow;
}
.box {
width: 100px;
background-color: black;
}
Here is fiddle with your code: jsfiddle

What does "this" do when used in function brackets?

I have a simple page with three buttons. I wanted to make one function that changes the background color of my page on a click. So i somehow made it work.
I am basically wondering what exactly "this" does when i use it in my changecolor brackets?
I kind of have a feeling what it does but i need more objective knowledge.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title>Panel</title>
<link rel="stylesheet" type="text/css" href="style.css"></link>
<script src="javascript.js"></script>
</head>
<body>
<h1>THIS IS SOME TEXT</h1>
<h2>This is some more text</h2>
<button class="buttons" id="button1" onclick="changecolor(this)">;P</button>
<button class="buttons" id="button2" onclick="changecolor(this)">;]</button>
<button class="buttons" id="button3" onclick="changecolor(this)">;)</button>
</body>
</html>
My css:
h1{
background-color: blue;
float: left;
}
h2{
color: blue;
float: left;
width:100%;
}
.buttons{
float:left;
margin-right: 10px;
width: 25px;
height: 25px;
}
#button1{
background-color:green;
}
#button2{
background-color:darkgray;
}
#button3{
background-color:blue;
}
My javascript:
function changecolor(clickedButton){
if(clickedButton.id == "button1"){
document.body.style.backgroundColor="lightgreen";
}
if(clickedButton.id =="button2"){
document.body.style.backgroundColor="gray";
}
if(clickedButton.id =="button3"){
document.body.style.backgroundColor="lightblue";
}
}
Thank you in advance!
In JavaScript this always refers to the “owner” of the function we're
executing, or rather, to the object that a function is a method of.
When we define our faithful function doSomething() in a page, its
owner is the page, or rather, the window object (or global object) of
JavaScript. An onclick property, though, is owned by the HTML element
it belongs to.
Via- http://www.quirksmode.org/js/this.html
this references the DOM element the event occurred on.
In this case, inside changecolor(), clickedButton will reference the <button> object that was clicked.
It sends a reference of the clicked element to the javascript function.
this refers to the button element itself.
this is changing your background color for the body of the document. "this" as in this button or object

Javascript change source image

I am trying to change the src= image of a parent in a nested ul li when I click on a link. Below is my code. I know how to change the src= with javascript, but I don't know how many tiers I need to navigate up to change the src= image. Example: I want to change src="test.png" when I click on Question1.Answer1.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
ul {
list-style: none;
margin: 0;
padding: 0;
}
li {
/*background-image: url(/images/page.png);*/
background-position: 0 1px;
background-repeat: no-repeat;
padding-left: 20px;
}
a {
color: #000000;
cursor: pointer;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.hidden {
display:none;
}
</style>
<script src="/js/jquery-1.11.1.js"></script>
<script type="text/javascript">
function addLine(what) {
$("#" + what).append('<li>URL to uploaded document</li>');
};
function myToggle(what){
$("#" + what).toggleClass('hidden');
};
function deleteLine(what) {
$(what).parent().children().remove();
}
</script>
</head>
<body>
<ul>
<li class="folder">
Test
<ul class="hidden" id="Test1">
<li class="folder"><img src="test.png">
Test1-2
<ul class="hidden" id="Test1-2">
<li>
This is Question 1
<ul id="Question1"><li onClick="deleteLine(this)"> Questoin1.Answer1</li></ul>
</li>
<li>
This is Question 2
<ul id="Question2"></ul>
</li>
<li>
This is Question 1
<ul id="Question3"></ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</body>
</html>
object with style property display or visibility: if hidden so no user-action-events possible.
Remove an object == remove from HTML DOM, so no user-action-events possible.
Add an object to HTML DOM so document must be new render. Same if object.style.display was changed.
display changes HTML DOM.
$("#" + what).append('URL to uploaded document'); this changes HTML DOM.
NOT same if object.style.visibility was changed: Visibility must have an exist object in HTML DOM.
please use
so, var imgPointer=document.getElementById("imgID");
put this pointer in an event handler to change imgPointer.src .
imgPointer (value if ID) is a pointer (value) relative to document an not to .
inside of addLine() change imgPointer.src .

Displaying text when link is clicked

This is inside my CSS:
div.hide {
display:none;
}
div.show {
color: #66CCFF;
}
This is in my HTML:
16:10
<script language="JavaScript">
function showText(show,hide)
{
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
</script>
<a name="16:10" onclick="showText('text1')" href="javascript:void(0);"></a>
<div id="text1" class="hide">This is your monitors aspect ratio.</div>
I'm trying to make the first link display the "This is your monitors aspect ratio." text lower on the page.
Any help is much appreciated.
Pure CSS Answer
Ok, if you just want to append text after you have moved to a position in a page using an anchor tag, you could do it with nothing but CSS similar to the following:
a:target:after{
content: " Test";
background-color: #ccffcc;
}
What this does is appends the text "Test" after the active anchor and colors. Here is an example page with implementation:
<!DOCTYPE html>
<html>
<head>
<title>Link Printer 2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
a:target:after{
content: " Test";
background-color: #ccffcc;
}
.bigSection{
height: 200px;
}
</style>
</head>
<body>
<div class="bigSection">
<div><a name="first">First</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
<div class="bigSection">
<div><a name="second">Second</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
<div class="bigSection">
<div><a name="third">Third</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
</body>
</html>
Answer using JavaScript
You need to bind an eventListener and prevent it from moving to the next page. Here is a way to do it with JavaScript or CSS. The JavaScript way will actually set the text to whatever you want. The CSS way will hide actually hide the element.
<!DOCTYPE html>
<html>
<head>
<title>Link Printer</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
.hide{
display: none;
}
</style>
<script>
function jsShowText(event) {
var divToManip = document.getElementById("text");
if (divToManip.innerHTML === "") {
divToManip.innerHTML = "Hello";
}
else {
divToManip.innerHTML = "";
}
event.preventDefault();
}
function cssShowText(event) {
var divToManip = document.getElementById("text");
if (divToManip.className === "") {
divToManip.className = "hide";
}
else {
divToManip.className = "";
}
event.preventDefault();
}
function setListeners() {
document.getElementById("jsPrinter").addEventListener("click", jsShowText, false);
document.getElementById("cssPrinter").addEventListener("click", cssShowText, false);
}
window.onload = setListeners;
</script>
</head>
<body>
<div><a id="jsPrinter" href="" onclick="showText();">Click With JavaScript</a></div>
<div><a id="cssPrinter" href="" onclick="showText();">Click With CSS</a></div>
<div id="text">I'm text</div>
</body>
</html>
"showText" must receive an id parameter to be used with the call to "document.getElementById"
Try this, just 1 link that will display the text below after click:
<a name="16:10" onclick="showText('text1')" href="javascript:void(0);">16:10</a>
<script language="JavaScript">
function showText(id)
{
document.getElementById(id).style.display = "block";
}
</script>
<div id="text1" style="display:none;">This is your monitors aspect ratio.</div>
I'm just using style display to hide/show the element. Hope it helps.
just change your css like this:
div.show {
display:block;
color: #66CCFF;
}
Here I am going to provide an example with something that I was working, thank you Alberto Montellano for the example, that gave me an idea, however what was required at the end was something a little different, with the option not to show the data and display it only when I click and make it disappear when click again. In this example I am going to give you two options; you can have a button or a link to trigger the JS function to display and hide the body text, you can choose if you want the button or link that is way I put a comment (optional), both behave as the same, it is up to you which one you want to use.
<!DOCTYPE html>
<html>
<head>
<!-- CSS -->
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top:20px;
}
</style>
</head>
<body>
<!-- text before the button or link -->
<p>Click the "PIN" button (or link) to display PIN options:</p>
<!-- The Pin button (optional) -->
<button type="button" onclick="myFunction()">PIN button:</button>
<!-- The Pin link (optional) -->
</br></br></br>
<a onclick="myFunction()" href="javascript:void(0);">PIN link:</a>
<!--Data will display or hide (toggle)-->
<div id="myDIV"style="display:none;">
These are the steps to get your PIN number: Bla bla bla.
</div>
<p><b>Note:</b> The text display when you click the button or link will take space, if you click again will be toggle.</p>
<!-- JS -->
<script>
function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
</body>
</html>

Categories

Resources