I am creating a JavaScript popup. The code is as below.
The HTML:
<div id="ac-wrapper" style='display:none' onClick="hideNow(event)">
<div id="popup">
<center>
<h2>Popup Content Here</h2>
<input type="submit" name="submit" value="Submit" onClick="PopUp('hide')" />
</center>
</div>
</div>
The CSS:
#ac-wrapper {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: url("images/pop-bg.png") repeat top left transparent;
z-index: 1001;
}
#popup {
background: none repeat scroll 0 0 #FFFFFF;
border-radius: 18px;
-moz-border-radius: 18px;
-webkit-border-radius: 18px;
height: 361px;
margin: 5% auto;
position: relative;
width: 597px;
}
The Script:
function PopUp(hideOrshow) {
if (hideOrshow == 'hide') document.getElementById('ac-wrapper').style.display = "none";
else document.getElementById('ac-wrapper').removeAttribute('style');
}
window.onload = function () {
setTimeout(function () {
PopUp('show');
}, 0);
}
function hideNow(e) {
if (e.target.id == 'ac-wrapper') document.getElementById('ac-wrapper').style.display = 'none';
}
The jsFiddle Link:
http://jsfiddle.net/K9qL4/2/
The Issue:
The above script works fine, but I need to make the popUp draggable.
Here's some code that will do what you want. It relies only on an object called drag to store all its values, but you can easily alter that. The example relies on there being a div with the id of mydiv (a document.write() is used in this instance to supply that) that has a position attribute of absolute or fixed. You can see it in action at Jamie
document.write("<" + "div id='mydiv' style='background:blue; width:100px;"
"height:100px; position:fixed;'>" + "<" + "/div>");
var drag = new Object();
drag.obj = document.getElementById('mydiv');
drag.obj.addEventListener('mousedown', function(e)
{
drag.top = parseInt(drag.obj.offsetTop);
drag.left = parseInt(drag.obj.offsetLeft);
drag.oldx = drag.x;
drag.oldy = drag.y;
drag.drag = true;
});
window.addEventListener('mouseup', function()
{
drag.drag = false;
});
window.addEventListener('mousemove', function(e)
{
drag.x = e.clientX;
drag.y = e.clientY;
var diffw = drag.x - drag.oldx;
var diffh = drag.y - drag.oldy;
if (drag.drag)
{
drag.obj.style.left = drag.left + diffw + 'px';
drag.obj.style.top = drag.top + diffh + 'px';
e.preventDefault();
}
});
Use the
.draggable();
jquery function, here is your updated fiddle:
http://jsfiddle.net/N9rQK/
If you don't want to use jQuery, you should read this subject: Draggable div without jQuery UI
Related
I tried to test changing backgroundColor and marginLeft on this simple example: https://jsfiddle.net/ntqLo6v0/2/
and couldn't make it work.
var collapsed = 0;
$('[data-toggle=collapse-button]').click(function() {
if (collapsed == 0) {
close();
} else {
open();
}
});
function close() {
document.getElementById("button").style.backgroundColor = "blue";
(document.getElementsByClassName("content")[0]).style.marginLeft = "20px";
collapsed = 1;
}
function open() {
document.getElementById("button").style.backgroundColor = "red";
(document.getElementsByClassName("content")[0]).style.marginLeft = "120px";
collapsed = 0;
}
.content {
background-color: green;
width: 200px;
height: 100px;
}
#button {
background-color: red;
width: 100px;
height: 50px;
margin: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button" data-toggle="collapse-button">
button
</div>
<div class="content">
some content here
</div>
There is just a little issue: $('[data-toggle=collapse-button]').
You are using jQuery but do not define it. That's why you get a Uncaught ReferenceError: $ is not defined in the console.
Here is your updated fiddle where I added jQuery (in the resources left) in order to make your example running.
When I click-drag (#cssNav) to the right, it is not moving proportionately along with the #html and #css div.
This might be something very obvious, but still am not able to figure it out, what am I missing here, please help?
Note: I don't want to use display:flex
codepen
$("#htmlNav").on("mousedown", dragStartH);
$("#cssNav").on("mousedown", dragStartH);
$("#jsNav").on("mousedown", dragStartH);
function dragStartH(e) {
e.preventDefault();
dragMeta = {};
dragMeta.pageX0 = e.pageX;
dragMeta.elem = this;
dragMeta.offset0 = $(this).offset();
dragMeta.codeWindow = "#" + $(e.target).attr("id").replace("Nav", "");
function handle_dragging(e) {
var change = e.pageX - dragMeta.pageX0;
var left = dragMeta.offset0.left + change;
$(dragMeta.elem).offset({ left: left });
$("#css").width($("#css").width() - change + "px");
$("#html").width($("#html").width() + change + "px");
}
function handle_mouseup(e) {
$("body")
.off("mousemove", handle_dragging)
.off("mouseup", handle_mouseup);
}
$("body").on("mouseup", handle_mouseup).on("mousemove", handle_dragging);
}
$(document).ready(function() {
var widthPercent = ($(window).width() - 30) / 3;
$("#html").width(widthPercent + "px");
$("#css").width(widthPercent + "px");
$("#js").width(widthPercent + "px");
});
html, body {
height: 100%;
margin: 0;
}
.container{
width:100%;
height: 100%;
background-color:#343;
display: flex;
flex-direction: column;
color: #fff;
margin: 0;
}
#preview, #code{
background-color:#433;
height: 50%;
width: 100%;
margin: 0;
}
#code{
border-bottom: #333 solid 2px;
width: 100%
}
#previewNav, #codeNav{
background-color:#bbb;
height: 10px;
width: 100%;
cursor: row-resize;
}
#html{
background-color: #BFB;
}
#css{
background-color: #FBB;
}
#js{
background-color: #BBF;
}
#html, #css, #js{
float: left;
width: 32%;
height: 100%;
}
#htmlNav, #cssNav, #jsNav{
background-color:#bbb;
float: left;
height:100%;
width: 10px;
cursor: col-resize;
z-index:10;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="codeNav"></div>
<div id="code">
<div id="htmlNav"></div>
<div id="html">H</div>
<div id="cssNav"></div>
<div id="css">C</div>
<div id="jsNav"></div>
<div id="js">J</div>
</div>
<div id="previewNav"></div>
<div id="preview">P</div>
</div>
This is how I would do it:
Keep track of which handle you press with navTypeand check if the user is holding its mouse down with dragging.
Then when the user moves the mouse in the document and it is holding its mouse down (dragging) it will move the #html, #css and #js accordingly
Change your javascript into this:
var mouseX, prevMouseX, navType, change;
var dragging = false;
$("#cssNav").mousedown(function () {
dragging = true;
navType = "css";
});
$("#jsNav").mousedown(function () {
dragging = true;
navType = "js";
});
$(document).mousemove(function (e) {
mouseX = e.pageX;
if(dragging){
e.preventDefault();
change = mouseX - prevMouseX;
if(navType == "css" && ($("#css").width() - (change)) > 0 && ($("#html").width() + (change)) > 0){
var hw = $("#html").width();
var cw = $("#css").width();
$("#html").width(hw + change);
$("#css").width(cw - change);
} else if(navType == "js" && ($("#css").width() + (change)) > 0 && ($("#js").width() - (change)) > 0){
var cw = $("#css").width();
var jw = $("#js").width();
$("#css").width(cw + change);
$("#js").width(jw - change);
}
}
prevMouseX = mouseX;
}).mouseup(function () {
dragging = false;
}).mouseleave(function () {
dragging = false;
});
My code is for a website where when you press the movement button the two squares will move and if you press the change colour button both squares will alternate colours. The shapes do these actions at the same time. However, only one square does this while the other does nothing... please help?
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: CadetBlue;
}
div#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: Maroon;
}
</style>
<style>
#containertwo {
width: 400px;
height: 400px;
position: relative;
background: CadetBlue;
}
div#animatetwo {
width: 50px;
height: 50px;
position: absolute;
left: 350px;
top: 0px;
background-color: Olive;
}
</style>
<body>
<p>
<button onClick="myMove()">Movement</button>
</p>
<p>
<button onClick="button_click()">Change Colour</button>
</p>
<div id ="container">
<div id ="animate"></div>
<div id ="animatetwo"></div>
</div>
<div id="box" onClick="button_click();"></div>
<script>
var colors = ["Maroon","Olive"];
function button_click() {
var box = document.getElementById("animate");
var background_color = box.style.backgroundColor;
var i = colors.indexOf(background_color);
if (i === colors.length-1) {
i = -1;
}
animate.style.backgroundColor = colors[i+1];
}
</script>
<div id="box" onClick="myMove();"></div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 1);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
<div id="box" onClick="button_click();"></div>
<script>
var colorstwo = ["Maroon","Olive"];
function button_clicktwo() {
var box = document.getElementById("animatetwo");
var background_color = box.style.backgroundColor;
var i = colorstwo.indexOf(background_color);
if (i === colorstwo.length-1) {
i = -1;
}
animatetwo.style.backgroundColor = colorstwo[i+1];
}
</script>
<div id="box" onClick="myMove();"></div>
<script>
function myMovetwo() {
var elem = document.getElementById("animatetwo");
var pos = 0;
var id = setInterval(frame, 1);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
</body>
</html>
Ok... I'll talk about the problem you're having first, then I'll try to give you some advice.
1) First of all upon clicking the "Movement" button you're only calling the myMove() function which is only responsible for moving the animated div, as you select it with:
var elem = document.getElementById("animate");
So if you desire to move both at the same time make sure you're activating the right functions, since I imagine you wanted to call myMovetwo() at the same time perhaps you could do:
function move() {
myMove();
myMovetwo();
}
That way you would call move() and both calls will run.
2) Now about your code, you should really consider isolating the different aspects of your page, and by that I mean isolating CSS, HTML and JavaScript, you can do that using the <link> tag to import your styles and the <script src="path"></script> tag to include your javascript code.
The other advice would be to remove onclick from your html tags and get the click event from your javascript code.
There are some great sources to learn this basics concepts, perhaps codecademy is a great one for starters https://www.codecademy.com/courses/html-javascript-css/0/1
Cheers!
I want to make a popup that should appear once a button is clicked and disappear once the user clicks outside of the box.
I'm not sure how to make the div disappear when I click outside of it.
var popbox = document.getElementById("popbox");
document.getElementById("linkbox").onclick = function () {
popbox.style.display = "block";
};
???.onclick = function () {
popbox.style.display = "none";
};
Here is the second version which has a transparent overlay as asked by the asker in the comments...
window.onload = function(){
var popup = document.getElementById('popup');
var overlay = document.getElementById('backgroundOverlay');
var openButton = document.getElementById('openOverlay');
document.onclick = function(e){
if(e.target.id == 'backgroundOverlay'){
popup.style.display = 'none';
overlay.style.display = 'none';
}
if(e.target === openButton){
popup.style.display = 'block';
overlay.style.display = 'block';
}
};
};
#backgroundOverlay{
background-color:transparent;
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
display:block;
}
#popup{
background-color:#fff;
border:1px solid #000;
width:80vw;
height:80vh;
position:absolute;
margin-left:10vw;
margin-right:10vw;
margin-top:10vh;
margin-bottom:10vh;
z-index:500;
}
<div id="popup">This is some text.<input type="button" id="theButton" value="This is a button"></div>
<div id="backgroundOverlay"></div>
<input type="button" id="openOverlay" value="open popup">
Here is the first version...
Here is some code. If there is anything else to add, please let me know :)
The event (e) object gives access to information about the event. e.target gives you the element that triggered the event.
window.onload = function(){
var divToHide = document.getElementById('divToHide');
document.onclick = function(e){
if(e.target.id !== 'divToHide'){
//element clicked wasn't the div; hide the div
divToHide.style.display = 'none';
}
};
};
<div id="divToHide">Click outside of this div to hide it.</div>
Here, the idea is to detect click events on the page and set the container’s display to none only when the target of the click isn’t one of the div descendants.
HTML
<div id="container">
<label>Enter your name:</label>
<input type="text">
<button id="submit">Submit</button>
</div>
JS
document.addEventListener('mouseup', function(e) {
var container = document.getElementById('container');
if (!container.contains(e.target)) {
container.style.display = 'none';
}
});
This is code I use to close my side bar when click outside
function openNav() {
document.getElementById("mySidebar").style.width = "100px";
document.getElementById("curtain_menu").style.marginLeft = "100px";
}
function closeNav() {
document.getElementById("mySidebar").style.width = "0";
document.getElementById("curtain_menu").style.marginLeft = "0";
}
document.onclick = function (e) {
if (e.target.id !== 'mySidebar' && e.target.id !== 'btn_frontpage_menu') {
if (e.target.offsetParent && e.target.offsetParent.id !== 'mySidebar')
closeNav()
}
}
.sidebar {
font-family: sans-serif;
height: 50%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
opacity: 0.9;
}
.sidebar a,
.dropdown-btn {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 1vw !important;
color: rgb(195, 195, 195);
display: block;
background: none;
width: 100%;
text-align: left;
cursor: pointer;
outline: none;
transition: 0.3s;
border: none;
}
.dropdown-container a {
color: rgb(174, 174, 174) !important;
}
.sidebar a:hover,
.dropdown-btn:hover,
.dropdown-container a:hover {
color: green !important;
/* background-color: #5c5c5c; */
}
.sidebar .closebtn {
position: absolute;
top: 12px;
font-size: 36px !important;
margin-right: 5px;
text-align: right;
right: 20px;
}
.openbtn {
font-size: 20px !important;
cursor: pointer;
background-color: transparent;
color: black;
padding: 6px 15px;
border: none;
float: left;
}
#main {
position :absolute;
width: 100%;
height: 100%;
left: 100px
}
<div id="mySidebar" class="sidebar" style="width: 100px;">
<a href="javascript:void(0)" class="closebtn"
onclick="closeNav()">×</a>
Home
<div class="dropdown-container">
Job Management
Request
Pending
</div>
</div>
<div id="curtain_menu">
<button id="btn_frontpage_menu" class="openbtn" onclick="openNav()">☰</button>
<div id="datetime"></div>
</div>
<div id="main"> Outside of 'Side Bar' is here
</div>
Here is my Solution.
yourFunc=e=>{
var popbox = document.getElementById("popbox");
if(e.target.id !=="popbox"){
popbox.style.display = "none";
}else{
popbox.style.display = "block";
}
}
document.addEventListener("click",yourFunc)
hope this will work for you
<script>
// Get the element
var modal = document.getElementById('modal');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
This code is tested and it's working nicely, thank you.
Could be done with onblur event.
// required for focus
divEl.setAttribute('tabindex', '1');
divEl.onblur = event => {
// hide only if blur occurred outside divEl, ignore its children
if (!event.currentTarget.contains(event.relatedTarget)) {
hide();
}
// re-focus, if a child took it
divEl.focus();
};
divEl.focus();
P.S. For IE11 a small hack event.relatedTarget = event.relatedTarget || document.activeElement; could be required.
<div class='icon alk-icon-close'>hidden hire</div>
document.addEventListener('click', function(e) {
var target = e.target.classList.value
if (target == 'icon alk-icon-close') ) {
hidden hire
}
});
plug this in
(function(){
// click outside of element to hide it
let hels = [];
window.hidable = (el, excepter, hider) => {
// hider takes el as the only arg
hels.push([el, excepter, hider]);
return el;
}
window.addEventListener('click', e=>{
for(let i = 0; i < hels.length; i++){
let el = hels[i][0];
let excepter = hels[i][1];
let hider = hels[i][2];
if(!el.contains(e.target) && excepter !== e.target){
hider(el);
}
}
});
})()
unit test
/* excepter is the element to trigger panel show */
// example implementation
window.hidable(panel_el, show_panel_button, el=>el.remove());
// other hiders can be:
el=>el.style.display = 'none';
// depends on your show implementation
el.onmouseleave = function(){
document.body.onclick = function(){
el.style.display = 'none';
document.body.onclick = null;
}
}
Okay, here's a jQuery based solution based on any div clicked within the DOM.
$('div').on('click', function(e){
var parents = $(e.currentTarget).parents();
for (var i = 0; i < parents.length; i++) {
if (parents[i].id === 'divToHide' || e.currentTarget.id === 'divToHide') {
// you are in the popup
};
}
e.stopPropagation();
});
This looks at your current element, as well as any of the parents, and checks if the id matches up. If divToHide is in the parents() list, then you keep the popup open.
*NOTE: This requires wrapping your content within a wrapper div or something similar.
Scenario
I am having a functionality in my project in which we have to add a note in a section and then it can be moved to the other sections. It is a sort of task tracking.
I am able to add a note dynamically created into one section and have made that note dragable. The note, sections are divs.
Problem
I am not able to drag the note to the other section or div. the note is draggable in its own section (div). Please help me with the solution so that it can be moved to other section.
Here is my HTML code:
<div id="addTaskDiv" style="height: 150px">
<a id="addTask" onclick="AddNote();">ADD Task</a> <a id="a1" onclick="AddText();">Submit</a>
</div>
<div id="MySplitter">
<div id="leftDiv" style="height: 150px; border-style: groove; width: 100%;">
left here
</div>
<div id="splitterUpperDiv">
<div id="midDiv" style="height: 150px; border-style: groove; width: 100%;">
middle here
</div>
<div id="rightDiv" style="height: 150px; width: 100%; border-style: groove;">
right here
</div>
</div>
</div>
Here is my .js
$().ready(function () {
$("#MySplitter").splitter();
$("#splitterUpperDiv").splitter();
$("#rightDiv").droppable();
$("#midDiv").droppable();
$("#leftDiv").droppable();
});
function AddNote(args, seder) {
var i = (typeof this.rel != 'undefined') && (this.rel - 0) == this.rel ? this.rel : 0;
var br = document.createElement("br");
$("#addTaskDiv")[0].appendChild(br);
addArea();
return false;
}
function addArea() {
var i = (typeof this.rel != 'undefined') && (this.rel - 0) == this.rel ? this.rel : 0;
var button = $(this);
var commentField = $('<textarea/>'); // create a textarea element
commentField[0].id = 'added' + i;
commentField
.css({
position: 'absolute',
width: 200, // textbox 200px by 100px
height: 100
})
// set the textarea's value to be the saved content, or a default if there is no saved content
.val(button.data('textContent') || 'This is my comment field\'s text')
// set up a keypress handler on the textarea
.keypress(function (e) {
if (e.which === 13) { // if it's the enter button
e.preventDefault(); // ignore the line break
button.data('textContent', this.value); // save the content to the button
$(this).remove(); // remove the textarea
}
})
.appendTo($("#addTaskDiv")[0]); // add the textarea to the document
}
function AddText() {
var i = (typeof this.rel != 'undefined') && (this.rel - 0) == this.rel ? this.rel : 0;
var a = $("#added0")[0].value;
var x = document.createElement("div");
x.width = '200px';
x.height = 'auto';
x.id = 'lable' + i;
this.rel = i + 1;
x.innerText = a;
var br = document.createElement("br");
$("#leftDiv")[0].appendChild(br);
$("#leftDiv")[0].appendChild(x);
$("#lable" + i + "").draggable();
}
You can try this :-
$("#rightDiv").droppable({
accept: '.draggableObject',
});
Please study this example code,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
section{
background: rgba(0, 0, 0, .1);
padding: 20px;
height: 350px;
margin: 20px 0 0 0;
border-radius: 20px;
}
#myDiv{
cursor: move;
background: red;
height: 150px;
width: 150px;
float: left;
}
#targetDiv{
background: red;
height: 300px;
width: 300px;
float: right;
}
</style>
</head>
<body>
<script>
window.onload = function(){
var count=0;
var myDiv=document.getElementById('myDiv');
var targetDiv=document.getElementById('targetDiv');
myDiv.addEventListener('dragstart', function(e)
{
/* change ui to see clearly */
this.style.opacity= 0.2;
this.style.borderStyle= 'dashed';
targetDiv.style.backgroundColor= 'yellow';
/* set text from this as an argument to transfer */
e.dataTransfer.setData("Text", this.innerHTML);
}, false);
myDiv.addEventListener('dragend', function(e)
{
/* change ui to see clearly */
this.style.opacity=1;
this.style.borderStyle= 'solid';>
targetDiv.style.backgroundColor='red';
/* change text of dragend div */
this.innerHTML="Total Count : "+ (++count) ;
}, false);
targetDiv.addEventListener('dragover', function(e)
{
/* change ui to see clearly */
this.style.backgroundColor='green';
if(e.preventDefault){ e.preventDefault(); };
},false);
targetDiv.addEventListener('dragleave', function(e)
{
/* change ui to see clearly */
this.style.backgroundColor='yellow';
}, false);
targetDiv.addEventListener('drop', function(e)
{
/* get text from dropped div */
this.innerHTML= e.dataTransfer.getData("Text");
if( e.preventDefault ){ e.preventDefault(); };
},false);
}
</script>
<div draggable="true" id="myDiv">
Drag able Area.
</div>
<div id="targetDiv">
Target Area.
</div>
</body>
</html>