Check box not being changed as I would expect - javascript

I am trying to make a simple widget that allows the user to select either the check box OR the whole div to change its value. I have the following code:
$(document).ready(function() {
$(document).on("click", ".inputCheck", function(event) {
event.stopImmediatePropagation();
event.preventDefault();
$(this).closest(".outter").trigger("click");
});
$(document).on("click", ".outter", function(event) {
console.log("inside");
event.stopImmediatePropagation();
event.preventDefault();
var $checkBox = $(this).find("input");
$(this).removeClass("selected");
$checkBox.prop("checked", !$checkBox.prop("checked"));
if ($checkBox.prop("checked"))
$(this).addClass("selected");
});
});
.outter {
width: 100px;
height: 100px;
border-style: solid;
border-width: 1px;
}
.outter:hover,
.inputCheck:hover {
cursor: pointer;
}
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="outter">
<input class="inputCheck" type="checkbox">
<div>This is a test</div>
</div>
</body>
</html>
It works as normal when the div is selected I.e. Checkbox changing values and a new class 'selected' being added to the .outter class. When the checkbox is selected I try to stop all defaults and propagation and then trigger the same code as selecting the div to change the class value. However the check box stays the same. Can someone please tell me why this isn't working and how to fix it?
Thanks

You don't need to stop propagation or anything. You can just check if the click was on the input or not, then change the input checked status like following. The click on the input will automatically be propagated to the parent div. You can check the click origin using event.target and make necessary actions.
$(document).ready(function() {
$(".outter").click(function(event) {
console.log('clicked');
var $checkBox = $(this).find("input");
$(this).removeClass("selected");
if (!$(event.target).is($checkBox)) {
$checkBox.prop("checked", !$checkBox.prop("checked"));
}
if ($checkBox.prop("checked"))
$(this).addClass("selected");
event.stopPropagation();
});
});
.outter {
width: 100px;
height: 100px;
border-style: solid;
border-width: 1px;
}
.outter:hover,
.inputCheck:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="outter">
<input class="inputCheck" type="checkbox" />
<div id="testIt">This is a test</div>
</div>

$(document).ready(function() {
$(document).on("click", ".inputCheck", function(event) {
event.stopImmediatePropagation();
$(this).closest(".outter").trigger("click");
});
$(document).on("click", ".outter", function(event) {
console.log("inside");
event.stopImmediatePropagation();
var $checkBox = $(this).find("input");
if ($checkBox.prop("checked"))
$(this).addClass("selected");
else
$(this).removeClass("selected");
});
});
.outter {
width: 100px;
height: 100px;
border-style: solid;
border-width: 1px;
}
.outter:hover,
.inputCheck:hover {
cursor: pointer;
}
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="outter">
<input class="inputCheck" type="checkbox">
<div>This is a test</div>
</div>
</body>
</html>

Related

How to prevent removing "section" from <div contenteditable> when editing?

How to prevent a user from removing <section> inside <div contenteditable> editor during editing (at least by pressing "Delete"/"Backspace" keys)?
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<style>
#editor {
width: 100%;
height: 300px;
border: 1px black solid;
}
#dont-remove-me-please{
width: 100%;
height: 100px;
border: 1px red dashed;
font-weight: bold;
user-select: none;
}
</style>
</head>
<body>
<div id="app"></div>
<div contenteditable="true" id="editor">
<div>hey guys!</div>
<div><strong>more text...</strong></div>
<section id="dont-remove-me-please" contenteditable="false">DONT' REMOVE ME!!!</section>
<div><br></div>
</div>
<script>
document.getElementById('editor').focus()
</script>
</body>
</html>
Thank You.
You can set contenteditable=false to children to prevent them from being editable.
However if you still want the children to be editable but the child dom elements shouldn't be removable I think you need to listen to backspace/delete events and see how these effect the dom and undo the changes if they remove dom nodes. Trying to figure this out myself
Edit: this is what I did
function onpaste(e: ClipboardEvent) {
e.preventDefault();
const selection = window.getSelection();
// Don't allow deleting nodes
if (selection.anchorNode.isSameNode(selection.focusNode)) {
// get text representation of clipboard
const text = e.clipboardData.getData("text/plain");
// insert text manually, but without new line characters as can't support <br/>s yet
document.execCommand("insertHTML", false, text.replace(/\n/g, ""));
}
}
function onkeydownInEditable(e: KeyboardEvent) {
if (e.key === "Enter") {
e.preventDefault();
}
if (e.key === "Backspace" || e.key === "Delete" || e.key === "Paste") {
const selection = window.getSelection();
// Don't allow deleting nodes
if (!selection.anchorNode.isSameNode(selection.focusNode))
e.preventDefault();
}
}
elementEditing.addEventListener("keydown", onkeydownInEditable);
elementEditing.addEventListener("paste", onpaste);
To achieve expected result, use below click event listener and add contenteditable attribute based on id
<script>
document.getElementById('editor').addEventListener('click', function(e) {
if(e.target.id !=="dont-remove-me-please"){
e.target.setAttribute("contentEditable", true);
}
}, false);
</script>
code sample - https://codesandbox.io/s/rypy7wkn5m
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<style>
#editor {
width: 100%;
height: 300px;
border: 1px black solid;
}
#dont-remove-me-please{
width: 100%;
height: 100px;
border: 1px red dashed;
font-weight: bold;
user-select: none;
}
</style>
</head>
<body>
<div id="app"></div>
<div id="editor">
<div>hey guys!</div>
<div><strong>more text...</strong></div>
<section id="dont-remove-me-please" contenteditable="false">DONT' REMOVE ME!!!</section>
<div><br></div>
</div>
<script>
document.getElementById('editor').focus()
</script>
<script>
document.getElementById('editor').addEventListener('click', function(e) {
if(e.target.id !=="dont-remove-me-please"){
e.target.setAttribute("contentEditable", true);
}
}, false);
</script>
</body>
</html>

change event is not fired on Microsoft Edge on first click

I am trying to implement drag and drop and browse files. I have a <div> with id #box and trying to trigger <input type="file" id="imageUpload" /> on click event of that <div>. The following code is working fine on Mozilla Firefox and Google Chrome but having problem on Microsoft Edge.
$(document).off().on('click', '#box', function () {
$('#imageUpload').trigger('click');
$('#imageUpload').off().on('change', function () {
var imageLoader = document.getElementById('imageUpload');
selectedFiles = imageLoader.files;
imageBrowseUploader(selectedFiles);
});
});
#box {
border: 1px dotted #0B85A1;
width: 100%;
height: 150px;
color: #92AAB0;
text-align: center;
font-weight: 500;
}
#imageUpload {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box">
<b>Drag and drop or click here</b> to upload your image.
</div>
<input type="file" id="imageUpload" />
Here is the working Demo with minor changes! (As you can see)
$(document).ready(function(){
$(document).on('click', '#box', function () {
//debugger;
$('#imageUpload').trigger('click');
});
$(document).on('change', function () {
debugger;
var imageLoader = document.getElementById('imageUpload');
selectedFiles = imageLoader.files[0].name;
imageBrowseUploader(selectedFiles);
});
});
function imageBrowseUploader(selectedFiles)
{
alert(selectedFiles);
}
#box {
border: 1px dotted #0B85A1;
width: 100%;
height: 150px;
color: #92AAB0;
text-align: center;
font-weight: 500;
}
#imageUpload {
visibility: hidden;
}
<html>
<head>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<div id="box">
<b>Drag and drop or click here</b> to upload your image.
</div>
<input type="file" id="imageUpload" />
</body>
</html>
Hope this will works for you! thank you :)
I would put the on change outside the click function, like this:
$(document).ready(function(){
$(document).off().on('click', '#box', function () {
$('#imageUpload').trigger('click');
});
$('#imageUpload').off().on('change', function () {
var imageLoader = document.getElementById('imageUpload');
selectedFiles = imageLoader.files;
imageBrowseUploader(selectedFiles);
});
});
#box {
border: 1px dotted #0B85A1;
width: 100%;
height: 150px;
color: #92AAB0;
text-align: center;
font-weight: 500;
}
#imageUpload {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box">
<b>Drag and drop or click here</b> to upload your image.
</div>
<input type="file" id="imageUpload" />
$(document).off().on('click', '#box', function () {
$('#imageUpload').trigger('click');
$('#imageUpload').off().on('change', function () {
var imageLoader = document.getElementById('imageUpload');
selectedFiles = imageLoader.files;
imageBrowseUploader(selectedFiles);
});
});
#box {
border: 1px dotted #0B85A1;
width: 100%;
height: 150px;
color: #92AAB0;
text-align: center;
font-weight: 500;
}
#imageUpload {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box">
<b>Drag and drop or click here</b> to upload your image.
</div>
<input type="file" id="imageUpload" />
Your above function contains event inside event.Please don't do that and initialize your change function inside document.ready function()

Allow dragstart-Event without loosing focus of other controls

I want to implement some draggable elements on the page, which should not break the currently focused control on the page. That is what I tried:
$('input').focus();
$('div').on('mousedown', function(event) {
// event.preventDefault(); // drag does not work anymore
// $('input').focus(); // focus still lost
});
div {
display: inline-block;
border: 1px solid green;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div draggable="true">Hello World</div><br />
The input field should not loose focus, when dragging "Hello World".<br />
<input type="text" />
If I activate event.preventDefault(), the focus is not lost on mousedown, but the drag operation cannot start anymore. Does anyone know how to solve this problem?
I guess, setTimeout will solve your problem
$('input').focus();
$('div').on('mousedown', function(event) {
window.setTimeout(
function() {
$('input').focus();
}, 1);
});
div {
display: inline-block;
border: 1px solid green;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div draggable="true">Hello World</div><br />
The input field should not loose focus, when dragging "Hello World".<br />
<input type="text" />
Result;
jsfiddle
Hope helps,
$(document).ready(function(){
$("div").on("mousedown",function(event){
event.preventDefault();
$("div").draggable();
$("input").droppable({
drop: function(event, ui) {
$("input").css('background', 'rgb(0,200,0)');
}
});
});
});
div {
display: inline-block;
border: 1px solid green;
padding: 10px;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div draggable="true">Hello World</div><br />
The input field should not loose focus, when dragging "Hello World".<br />
<input type="text" />

javascript how do i use the hover element on a div-element using a script with namespace?

In this code i change the color of my div while hovering the mouse over it. How can i achieve this without using style and instead put it in a script with namespace?
<html>
<head>
<title></title>
<style type="text/css">
.link-container {
border: 1px solid;
width: 50%;
height: 20px;
}
.link-container a {
display: block;
background: green;
height: 100%;
text-align: center;
}
.link-container a:hover {
background: red;
}
</style>
</head>
<body>
<div class="link-container">
<a>hover to change color</a>
</div>
</body>
</html>
You can use mouseover event of the element.
[].forEach.call(document.getElementsByClassName('link-container'),function(e){
e.addEventListener("mouseover", function(){
this.style.background='red'
});
});
EDIT:
You need mouseout event to remove the applied style.
[].forEach.call(document.getElementsByClassName('link-container'),function(e){
e.addEventListener("mouseover", function(){
this.style.background='red'
});
e.addEventListener("mouseout", function(){
this.style.background='inherit'
});
})
add eventListeners and have then fire functions in your namespace (say myApp)
var myApp = {
hover: function(event){
event.target.setAttribute("style", "background-color:red;")
},
out: function(event){
event.target.setAttribute("style", "background-color:green;")
}
}
var item = document.getElementById("btn");
item.addEventListener("mouseover", myApp.hover, false);
item.addEventListener("mouseout", myApp.out, false);
Plunker here

addEventListener to right click event

I would like to add event listener to a right click event, i know how to deal with a simple click:
document.getElementById("myBtn").addEventListener("mousedown", function(){ });
What about a right click event ?
Listen to the contextmenu event.
Just testing the click type using :
alert("You pressed button: " + event.button)
<!DOCTYPE html>
<html>
<head>
<style>
div { background: yellow; border: 1px solid black; padding: 10px; }
div {
background: yellow;
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div oncontextmenu="myFunction(event)">
<p>Right-click inside this box to see the context menu!
</div>
<script>
function myFunction(e) {
e.preventDefault();
//do something differant context menu
alert("You right-clicked inside the div!");
}
</script>
<!--if it helpful visit once http://topprojects.ml for more stuf-->
</body>
</html>
document.body.addEventListener("mousedown", event => {
if (event.button == 0) { // left click for mouse
doSomething;
else if (event.button == 1) { // right click for mouse
doAnotherThing;
else { // other buttons on the mouse
doOtherThings;
}
}

Categories

Resources