Technology I am using is materialize and vanilla js. I've created a materialize button that opens a model. within the model is a form that takes user input, then places the input text onto the main page, when the Submit button is triggered. then I have a button that should remove/delete the input posted. So the issue I'm having is that the JavaScript linked to the button which should delete/removeChild isn't working. please help :)
// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', () => {
var elems = document.querySelectorAll('.modal');
var instances = M.Modal.init(elems);
});
//Delete From The Dom
const delExerciseBtn = document.querySelector('.del-exercise-btn');
delExerciseBtn.addEventListener('click', (e) => {
if(e.target.className == 'delete'){
const h6 = e.target.parentElement;
delExerciseBtn.removeChild(h6);
}
});
// Add User's To the Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');
const disabledExersiceBtn = document.querySelector('.disabled-exersicebtn');
exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();
// Get Input Value
const value = exerciseForm.querySelector('input[type="text"]').value;
// Create Elements
const h6 = document.createElement('h6');
// Add Content
h6.textContent = value;
// Append To Dom
addExerciseDom.appendChild(h6);
//Disable Btn
disabledExersiceBtn.setAttribute('disabled', 'disabled');
});
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<!-- Google icons -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Sytle.css -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!----- user's input ------->
<div class="row">
<div class="col s12 center valign-wrapper center-align">
<div class=" exercise-dom delete"> <!--Users text input h6----> </div>
</div>
</div>
<!-- Btn/Modals/form -->
<div class="row">
<!-- Dom Btn -->
<div class="col s12 center ">
<a href="#exercise" class="btn-floating btn-small darken-4 z-depth-2 black center modal-trigger disabled-exersicebtn">
<i class="material-icons white-text">add </i>
</a>
</div>
<!-- Modal/form -->
<div class="modal modal-position" id="exercise">
<div class="modal-content">
<div class="row exercises-padding">
<form class="col s12 exercises-form" autocomplete="off">
<div class="input-field col s10">
<i class="material-icons prefix">fitness_center</i>
<input type="text" id="autocomplete-input" class="autocomplete center">
<label for="autocomplete-input" ><h6>Exercises</h6></label>
</div>
<div class="modal-footer">
<input class="modal-close btn black" type="submit" value="Submit">
</div>
</form>
</div>
</div>
</div>
<!-- Remove Users Btn -->
<div class="col s12 center remove-padding">
<a href="#" class="btn-floating btn-small darken-4 z-depth-2 black center modal-trigger del-exercise-btn">
<i class="material-icons white-text ">remove </i>
</a>
</div>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<!-- app.JavaScript -->
<script src="app.js"></script>
</body>
</html>
Update:
you have a nesting error in your HTML, a </div> is missing, which is why the DOM doesn't contain the form
check the DOM with developer tools by inspecting elements, and you'll see that the structure is wrong
you can also use for example Codepen's "Analyze HTML" function in the HTML pane to check your HTML
the <form>'s class is Exercises-form, and the selector .exercises-form (from const exerciseForm = document.querySelector('.exercises-form');) therefore can't find the element, as CSS class names are case-sensitive. exerciseForm then becomes null, which causes the error Uncaught TypeError: Cannot read property 'addEventListener' of null
the delete button still doesn't work. I suggest to you try for yourself. Use the browser developer tools, especially the DOM element inspector and the console for interactive tests for your selector queries (and the element you select in the element inspector is accessible as $0 in the console.). There are many tutorials a Google search away.
Additional note: I oversaw that there's already an document.addEventListener('DOMContentLoaded', () => {... at the top of the file. You can put your code there, no need for another DOMContentLoaded event listener (although it doesn't hurt either).
Original answer:
You get
Uncaught TypeError: Cannot read property 'addEventListener' of null
that means that
const delExerciseBtn = document.querySelector('.del-exercise-btn');
couldn't find the node and returned null.
Probable reason: code runs too early, browser has not yet constructed the DOM.
Solution: wrap your code in a DOMContentLoaded event handler:
window.addEventListener('DOMContentLoaded', (event) => {
const delExerciseBtn = document.querySelector('.del-exercise-btn');
// ...
});
const h6 = e.target.parentElement;
delExerciseBtn.removeChild(h6);
You are trying to remove its parent from a button. And you need to remove the button from the parent.
const h6 = e.target.parentElement;
h6.removeChild(e.target);
Related
Let's say, I have the following html document:
<div id="container" class="container">
// here comes the mxGraph
</div>
<div class="button-container">
<button id="myButton" type="button" name="button" onclick="myFunction()">Save</button>
</div>
</body>
Is there a way to catch the click-event of myButton in mxGraph?
Yes, you can catch event outside the mxgraph-div.
Do the following inside the jquery $(document).ready function:
Declare the graph has a global variable.
Create a function to load the graph inside the mx-graph div
Create the function for the external button click event.
Bind the function click event to the Step 3 Created function
Call the Step 2 function to load the mx-graph inside the div.
In the Step 3 function, you can access the graph object to trigger an xml save
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<ol class="breadcrumb">
<button id='genxml' class="btn btn-outline-success btn-sm m-2" onclick="this.blur();">
<span class="fas fa-fw fa-folder"></span> Download XML
</button>
</ol>
<div class="container">
<div class="row">
<div id="graphContainer" class="col-md-12" style="float:left;position:absolute;overflow:scroll;width:80%;height:80vh;cursor:default;outline:1px solid red">
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var graph;
function downloadXML(){
// access the Graph object here to save the mxUtils
// Block of Code to get the mxGraph mxUtil in the function
// var node = encoder.encode(graph.getModel());
// mxUtils.popup(mxUtils.getPrettyXml(node), true);
}
function main(container){
// Block of Code to load a mxGraph in the Container
/* graph = new mxGraph(container);
graph.getModel().beginUpdate();
var v1 = graph.insertVertex(parent, 'r', req,req_grp_geo.x+30, req_grp_geo.y+40, 160, 40,'part_group');
var v2 = graph.insertVertex(parent, 'f', func,func_grp_geo.x+30, func_grp_geo.y+40, 160,40,'functional_group' );
graph.getModel().endUpdate();*/
}
$('#genxml').on('click', function(){
downloadXML();
});
main(document.getElementById('graphContainer'))
});
</script>
I'm trying to get the child image of a clicked div.
I want to get it's src value. But it's returning undefined.
Could someone point me in the right direction?
Tried using Jquery .find() https://api.jquery.com/find/
Tried using Jquery .children() https://api.jquery.com/children/
Both return undefined.
for (let i = 0; i < $('#draw-raster > div').length; i++) {
$(document).on('click', '#raster-item'+i, () => {
let image = $(this).children('img').attr('src'); //undefined
let image2 = $(this).find('img').attr('src'); //undefined
if (image) {
console.log(image);
return alert("image child found!");
}
return setTimeout(() => {
$('#raster-item'+i).children('img').hide();
}, 4500);
});
$('#image'+i).hide();
}
load html:
for(let i = 0; i < 16; i++)
{
let image = displayImages();
$('#draw-raster').prepend(
"<div id=raster-item" + i + " class='imageh"+i+"' data-id=" + i + "><img src='"+ displayImages() +"' class='image "+i+"' id='image"+ i +"' alt='Failed to load image' width='173.19' height='107.3'></div>"
);
}
html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Memory</title>
<script src="inc/js/jquery.min.js"></script>
<link rel="stylesheet" href="inc/css/boostrap.min.css">
<link rel="stylesheet" href="inc/css/memory.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="container justify-content-center">
<div class="wrapper">
<div class="row">
<div class="col-lg-9">
<div class="card">
<div class="card-header bg-dark" style="color:white;">
<h2>Memory</h2>
</div>
<div class="card-body">
<section class="col-12 mx-auto" id="draw-raster">
</section>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<div class="card-header bg-dark" style="color:white;">
<h2>Turns</h2>
</div>
<div class="card-body">
<div id="turns">Turns: 0</div>
<div id="sets">Sets: 0</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-success col-12" type="button" id="reset">Reset scores</button>
</div>
</div>
</div>
</div>
</div>
<script src="inc/js/memory.js"></script>
</body>
</html>
Both attempts return undefined, i'm uncertain what would work.
Yes, I've been spamming google too. :'^)
A couple of notes on your code:
1) If you want to use this you'll need to switch from an arrow function back to a regular anonymous function. Arrow functions don't have a this of their own and will borrow the context from their outer lexical environment. It's why your code keeps return undefined.
2) You don't need a loop. The benefit of using jQuery is that you can operate on collections of elements all at once. In your case you're attaching a single event listener to a parent element (here: document) and waiting for events to bubble up from the .raster-item imgs and be "captured". This is called event delegation and is useful when you want to process new elements added to the DOM after it has loaded.
2) You will find it easier to use a class instead of many ids.
Here's an example based on your code with these changes:
// Use event delegation to add an event listener to the element with
// the container class that watches out for click events on **all**
// elements with the raster-item class that contain images
$('.container').on('click', '.raster-item img', function () {
// `$(this)` will be the image element, so simply grab its src
// from the attribute
console.log($(this).attr('src'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="raster-item"><img src="https://dummyimage.com/50x50/555/fff.png" /></div>
<div class="raster-item"><img src="https://dummyimage.com/50x50/777/fff.png" /></div>
<div class="raster-item"><img src="https://dummyimage.com/50x50/999/fff.png"/></div>
<div class="raster-item"><img src="https://dummyimage.com/50x50/bbb/fff.png" /></div>
</div>
You don't need jQuery for this. You can harness the power of event bubbling with vanilla JavaScript.
In the web page below, the code inside the script tags, listen for a click event and runs some code if that event happens, i.e. bubbles, through a DIV element:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Clicked div img</title>
</head>
<body>
<div class="catcher">
<p>This is a div with an image inside</p>
<img src="image-to-pick.jpg" alt="image to pick" ()>
</div>
<script>
document.addEventListener('click', function (event) {
if (event.target.tagName == 'DIV') {
var imgToPick = event.target.querySelector('img');
console.log(imgToPick.src); // add your code here
}
}, false);
</script>
</body>
</html>
In other words, you trigger a "click event" whenever you click on that page, that event bubbles up until it reaches the root of the HTML document (which you can imagine as an upside-down tree where the root is the html tag).
If you don't need or don't want to let it bubble to the elements "above" you DIV, you can also stop the propagation of that click event by using event.stopPropagation(), right after you handle the img src.
You can find more info about how this works here on MDN (Mozilla Dev. Network)
I'm not quite sure in what context you need to do this, but with jquery it's pretty straight forward.
If you have multiple images within a parent div, you can set the child images as the selecters for the click event, and return each image src when clicked on directly.
The resulting jquery is only three lines long this way, and you can add as many images as you like to the parent div:
<div class="image-container">
<img id="first" src="first-source-goes-here.jpg" alt="img text" />
<img id="second" src="second-source-goes-here.jpg" alt="img text" />
<img id="third" src="third-source-goes-here.jpg" alt="img text" />
</div>
$(".image-container > img").click(function() {
// replace 'alert' with what ever you need it to be
alert( $(this).attr("src") )
})
EDIT:
In response to Andy's comment on my answer below, if you are loading images once the DOM has been loaded, then you could run a check on the click parent div to see if there are any images within it before returning the source:
$(".image-container").click(function() {
if( $(this).children("img").length > 0 ) {
alert( $(this).find("img").attr("src") )
} else {
alert('there are no images here')
}
})
The idea is next:
There are two dropdown lists, which populated dynamically, first one only once, when the page is loaded, but second dropdown list should be populated dynamically every time when first list is clicked, and its content depends on selected item in the first list and I use jQuery to populate dropdown lists dynamically.
All content on the entire page wrapped on several tabs and contains the TinyMCE Editor. I tried to use jQuery with different versions of MaterializeCSS, but I met different issues (broken layout or "not clickable / dropping down" lists).
Using M instance without jQuery fixed all previous issues but I didn't find documentation on how to handle the onClick event with it and how to initialize again the dynamically updated dropdown lists?
HTML:
<!-- In head: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css"> -->
<!-- First Dropdown list -->
<div class="col s4 m2">
<div class="nav-wrapper mar-top-20">
<!-- https://materializecss.com/dropdown.html -->
<!--Dropdown Trigger -->
<a id="rec-years-trigger" class="dropdown-trigger waves-effect waves-light btn w100 avio" href="#" data-target="dropdown1">
<?=data.currentMonth ?> <i class="medium material-icons right">arrow_drop_down</i>
</a>
<!-- Dropdown Structure -->
<ul id="dropdown1" class="dropdown-content"></ul>
</div>
</div>
<!-- Second Dropdown list -->
<div class="col s6 m8">
<div class="nav-wrapper mar-top-20">
<!-- https://materializecss.com/dropdown.html -->
<!--Dropdown Trigger -->
<a id="post-list-trigger" class="dropdown-trigger waves-effect waves-light btn w100 avio" href="#" data-target="dropdown2">
Posts<i class="medium material-icons right">arrow_drop_down</i>
</a>
<!-- Dropdown Structure -->
<ul id="dropdown2" class="dropdown-content icons"></ul>
</div>
</div>
JavaScript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
...
document.addEventListener('DOMContentLoaded', function() {
//generate a list:
for (var i = 0; i < recYears.length; i++) {
var newValue = recYears[i];
var el = '<li>' + newValue + '</li>';
$("#dropdown1").append(el);
};
var elems = document.querySelectorAll('.dropdown-trigger');
var instances = M.Dropdown.init(elems, {
belowOrigin: true
});
//Somewhere here OnClick EventHandler to populate second Dropdown list dynamically...
});
I'm trying to understand modals and js better. I have tried to use buttons that are realated to php files in order to make the content of the php files appear in a modal window once the button is clicked.
so...
button_1 gets file_1 and puts it in modal once it is clicked.
button_2 gets file_2 and puts it in modal once it is clicked.
etc.
I have acheived most of this but for some reason, each button needs to be clicked twice (for the first appearence of the modal window) for the modal to work. Afterwards, a simple click works fine, until the page is refreshed. At that point, two clicks are again needed.
My code works fine if I don't try to insert the information from the php file into a modal window. So... I'm guessing it is releated to the fact that the button has to do two things. 1. get the info and 2. open the modal window.
How do I combine both in one click?
I have tried to prefech files.
<link rel="prefetch" href="/folders/to/php/files/1.php">
I have also tried to pre-insert the modal in the html .
I have tried to use the load instead of click in the function.
I my tries have not changed the fact that I need to double click the buttons at first.
Any help appreciated!!
BONUS:
If I could get the buttons to dynamically find their related file, that would be bonus. Meaning I could simply add or remove buttons and they would find the correct files. All I would need to do is to add as many files as buttons.
Thanks for your time and help!
Here are the codes:
$("#liste > button").on('click', apar);
function apar() {
$(this).addClass("active").siblings().removeClass("active");
$('#main_p').load("/folders/to/php/files/" + (1 + $(this).index()) + ".php");
$(document).ready(function() {
// Do something with the DOM
$('.active').click(function() {
});
});
}
function renderHTML(data) {
var htmlP = data.url;
$('#main_p').html(htmlP);
}
// On page load, click on the first `btn` to automatically load the data for it
$('#liste > button:first').click(renderHTML);
.btn {
margin: 5px;
padding 0px 5px;
text-align: center;
background-color: #0095ff;
color: #FFF;
border: none;
}
.btn:hover,
.btn:focus {
outline: none !important;
color: #FFF;
}
.active {
background-color: #891;
}
<!doctype html>
<html>
<head>
<title> Modals </title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div id="liste">
<button class="btn" data-toggle="modal" data-target="#myModal_1">
<div class="tree">to file 1</div>
</button>
<button class="btn" data-toggle="modal" data-target="#myModal_2">
<div class="tree">to file 2</div>
</button>
<button class="btn" data-toggle="modal" data-target="#myModal_3">
<div class="tree">to file 3</div>
</button>
<h4 id="main_tit"></h4>
<div class="main_p" id="main_p"></div>
<div id="main_ima"></div>
<script src="js/main.js" async></script>
</body>
</html>
here is the example of a 1.php file:
<div id="myModal_1" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Look 1</h4>
</div>
<div class="modal-body">
<?php
echo "I have the 1.php <br>";
echo "its a go!";
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
UPDATE: I have added the automatic selection on button. So I have removed the button attributes in the html and have added this at the top of the JS:
var idVar = $("#liste").find("button").each(function(index){
$(this).attr("data-target","#myModal_" + (1+$(this).index()));
$(this).attr("data-toggle","modal");
$(this).attr("class","btn");
});
At the top of your js file there is $("#liste > button").on('click', apar);
Try to change it to:
$('body').on('click', '#liste > button', apar);
And put it at the end of your code after your $('#liste > button:first').click(renderHTML);
Let me know if this doesn't fix it.
Edit: Try creating new custom class for those buttons in HTML. It is good to set a marker to your custom classes, something like l-custom-class, or customClass, try to follow this example:
HTML:
<div id="#liste">
<button type="button" class="l-liste-button">btn1</button>
<button type="button" class="l-liste-button">btn2</button>
<button type="button" class="l-liste-button">btn3</button>
</div>
JS:
function apar(){
//some code for apar function..
}
function renderHTML(){
//some code for renderHTML function
}
$('body').on('click', '.l-liste-button', apar);
$('body').on('click', '.l-liste-button:first', renderHTML);
Here is JSFiddle
I am trying to trigger an event with a button that takes text from a textarea and sends it to a panel using the Bootstrap Framework (v.3.3.7). Currently trying to do this using an event listener in Javascript rather than assigning an ‘onclick’ value for the button.
HTML:
<div class="container-fluid">
<div class="row">
<!-- Panel where text will be appended to -->
<div id="mainChatBox" class="panel-body" style="height:435px; overflow-y:scroll"></div>
<!-- Textarea and button -->
<div class="panel panel-footer" style="height:40px">
<div class="form-group col-md-10 col-lg-10">
<input type="text" placeholder="Type your message here" class="form-control" id="messageBar" />
</div>
<div class="input-group-btn col-md-2 col-lg-2">
<button id="sendMessageButton" class="btn btn-default">Send</button>
</div>
</div>
</div>
</div>
Javascript
var sendMessageButton = document.querySelector('#sendMessageButton');
var messageBar = document.querySelector('#messageBar');
var mainChatBox = document.querySelector('#mainChatBox');
sendMessageButton.addEventListener("click", function (event) {
var message = messageBar.value;
mainChatBox.innerHTML += message + "<br />";
});
I tried debugging by using this code and another version where I instead assign the button an ‘onclick’ value and then keep the function for it.
Here is a link to a reddit post with that version of code where I tried to find a solution with assigning an ‘onclick’ value to the button instead of using an EventListener.
Reddit post link
I need to know why when the event is triggered by the button that the text will not be appended to the mainChatBox when using either the method with the 'onclick' value assignation to the "button" tag for sendMessageButton, or the EventListener in the Javascript.