Close toggle when clicking away from div - javascript

I have a calendar that opens up when the input is clicked, and it can be closed by a cross(X. I need the calendar to close when clicking anywhere else on the page. I have tried various methods on Stackoverflow but I think there are conflicts with the original scripts. I'm guessing there is something I can add to the closeClaendar function to close when outside of div?
function closeCalendar(calendarId) {
$("#" + calendarId).hide();
}
function CalendarMonthChanged(contract, product, dropdtls, form, ticketType, dateselectorid) {
$calendar = $("#CalendarWrapper");
var loader = '<%= Html.StaticImage(Url, "ajax-loader.gif") %>';
$calendar.find(".table").html("<div class = 'calendar-loading' style='width:175px;'><img src = '" + loader + "' /></div>");
var qty = 2;
var dataArray = {
contract: contract,
productId: product,
dropdtls: dropdtls,
formNumber: form,
ticketType: ticketType,
numTickets: qty,
dateSelectorId: dateselectorid
};
$.ajax({
type: "POST",
url: '<%= Url.Action("Calendar", "productapi", null) %>',
data: dataArray,
success: function (response) {
$calendar.html(response);
toggleLayer("CalendarForm1");
}
});
}
<div id="CalendarWrapper">
<div id="Allocation">
<div id="CalendarForm1" class = "CalendarForm" style="display:none;">
<div class="allocation_form bg">
<div class="calendar_header">
<a href="javascript:closeCalendar('CalendarForm1');">
<span class="m-xs-10 halflings remove red"></span>
</a>
<select name="calendar_month" class="form-control" onchange="CalendarMonthChanged('<%= Model.ContractID %>','<%= Model.AWItemId %>',this.value,'<%= Model.FormNumber %>', '<%= Model.TicketType %>', <%= (int)Model.DateSelector %>); ">
<%= Model.Months %>
</select>
</div>
<div id="Loading" class="Loading" style="width:175px;height:172px;display:none;"></div>
<%= Model.Days %>
</div>
</div>
</div>
</div>

Here is one easy way by adding a click handler to document.
jsFiddle: http://jsfiddle.net/6pcq7pvo/3/
$(document).on("click", function (e) {
if ($("#calendar").is(":visible") && !$(event.target).is('#calendar *, #calendar')) {
// user clicked somewhere in the document but not inside the calendar
$("#calendar").hide();
$("#btnOpenCalendar").show();
} else if (event.target.id === "btnOpenCalendar") {
// user clicked the "Show calendar" button
$("#btnOpenCalendar").hide();
$("#calendar").show();
}
else if ($(event.target).is('#calendar span'))
{
// user clicked a date in the calendar
// for demo purposes only; normally your calendar plugin handles this for you
alert("Clicked date: " + $(event.target).text());
}
});
#calendar {
height: 100px;
width: 100px;
border: 1px solid black;
background-color: #ccc;
display: block;
overflow: hidden;
}
#calendar span {
display: inline-block;
width: 17px;
border:1px solid #ddd;
cursor: pointer;
}
#btnOpenCalendar { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>click anywhere in this frame, but outside of the "calendar" (gray box) to close calendar</h3>
<div id='calendar'><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span>
</div>
<input id='btnOpenCalendar' type='button' value='Show calendar' />

Try this:
$(document).click(function(){
if($("#" + calendarId).is(':visible')){
$("#" + calendarId).hide().css("visibility", "hidden");;
}
});
also on your anchor click do, following to avoid hiding the calendar again:
$(document).on('click', 'a', function (e) {
//show calendar
$("#" + calendarId).show()
e.stopPropagation();
});
or instead of e.stopPropagation(); you can also use e.preventDefault();

Related

Load ASP.NET MVC Partial Views Dynamically Using JQuery

I have a view with a test link on the left side. Each time user clicks the test link, I am adding a tab button and tab content (straight up HTML5 and CSS). This is what it looks like:
Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MDMS_Web.Controllers
{
public class MainViewController : Controller
{
//
// GET: /MainView/
public ActionResult MainView(string name)
{
ViewBag.Name = name;
return View();
}
//[ChildActionOnly]
//public PartialViewResult MainContentPartial()
//{
// return PartialView("~/Views/MainView/MainContentPartial.cshtml");
//}
public ActionResult GetView()
{
return PartialView("~/Views/MainView/MainContentPartial.cshtml");
}
}
}
Partial View
<div id="MainContentBox" style="margin: 0em 0em;">
<h2>Testing</h2>
</div>
Main View
#{
ViewBag.Title = "Main View";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<main id="mainView">
<div class="row" style="min-width: 100%; ">
<div style="float: left; width: 20%; min-height: 870px; margin-top: 0.5em; margin-left: -1em; overflow: hidden; border-style: solid; border-width: thin; border-color: lightgray; ">
<div id="Test">
<div class="row" style="background-color: #c2cbfb; margin-left: 0; margin-right: 0; ">
<p id="menuTitle" style="width: 100%; text-align: center; margin: 5px 0 5px 0; ">Test</p>
</div>
<div class="row content-wrapper">
<span style="white-space: nowrap;">
<img class="icon" style="width: 30px; height: 30px; " src="Content/images/dashboard/CheckIcon.png" alt="Check icon" />
<a id="TestLink">Test Stuff</a>
</span>
</div>
</div>
</div>
<div style="float: left; width: 80%; min-height: 870px; margin-top: 0.5em; margin-left: 0em; overflow: hidden; ">
<div id="MainContentBox" style="margin: 0em 0em;">
<div id="tabs" class="tab">
</div>
<div id="content">
</div>
</div>
</div>
</div>
<div id="loading">
</div>
</main>
#section scripts{
#Scripts.Render("~/bundles/App/MainView")
<script type="text/javascript">
$(function () { MainView.initModule('#ViewBag.Name') });
</script>
}
JavaScript
function addTab(evt) {
stateMap.tabIndex += 1;
// add tab button
console.log(evt);
var tHtml = '<button id="tb' + stateMap.tabIndex + '" class="tablinks">' + "New Tab " + stateMap.tabIndex + '</button>';
$("#tabs").append(tHtml);
console.log("we have a new tab!");
// add tab content section
var node = document.createElement('div');
node.setAttribute('id', 't' + stateMap.tabIndex);
node.className = "tabContent";
// load partial page place holder
var contentPlaceHolder = document.createElement('div');
contentPlaceHolder.setAttribute('id', 'c' + stateMap.tabIndex);
node.appendChild(contentPlaceHolder);
document.getElementById("content").appendChild(node);
console.log("we have new content placeholder for partial view!");
// HERE IS WHERE MY PROBLEM BEGINS !!!!!!
// NOTHING I DO WILL LOAD MY PARTIAL PAGE !!!!
//#{ Html.RenderPartial("MainContentPartial"); }
//$("#c" + stateMap.tabIndex).load('#{ Html.RenderPartial("MainContentPartial"); }');
//$("#c" + stateMap.tabIndex).load("GetView");
$(function () {
$("#c" + stateMap.tabIndex).load(
'<%= Url.Action("GetView", "MainViewController") %>'
);
})
//url: 'MainViewController/GetView',
//$.ajax({
// url: 'GetView',
// dataType: 'html',
// success: function (data) {
// $("#c" + stateMap.tabIndex).html(data);
// }
//});
}
JavaScript initModule
var initModule = function (data) {
stateMap.currentSection = data;
//Bind events
$("#TestLink").on("click", function (event) {
addTab(event);
});
$(document).ready(function () {
$(".tab").on("click", "button", function (event) {
openTab(event);
});
});
};
return { initModule: initModule };
My issue is with the last part of the JavaScript and probably the Controller. Can someone please tell me the correct way to load the partial view into my dynamically created tab content using JQuery?
You can load Partial View dynamically using Jquery in following way
$(document).on("click", "#TestLink", function () {
var url = "/MainView/GetView";
$.get(url, function (data) {
$("#content").html(data);
});
});
Here URL is the URL of action which will return PartialView.

New message background highlighting

I have created a comment system using ajax and php with the usage of append system now I am looking to make it look more attractive so I want when ever a new comment is posted it should be highlighted background like background color fadein and then fadeout smoothly like whenever new answer is posted it is highlighted with an orange background color can anyone help me out how it would be done and what jquery function is used
my jquery
$(document).ready(function() {
$('#sub_comment').on('click', function() {
var comment = $('#comment').val();
var store_id = $('#store_id').val();
$(document).ajaxStart(function() {
$('#wait').css('display', 'block');
});
$(document).ajaxComplete(function() {
$('#wait').css('display', 'none');
});
$.ajax({
type : "POST",
data : {comment: comment, store_id: store_id, command: 'Comment'},
dataType : 'text',
url : "includes/get_data.php",
success : function(data) {
$('#comment').val('');
$('#comments').append($(data).hide().fadeIn(2000));
}
});
});
});
you can use the transition: background-color 1s linear; css property.
Set initial background to the comment div and add the above property. Then change the background (to orange) of the div, it will create a fadein effect and after some setTimeout remove this background, then it will create a fadeout effect.
Check this example for reference.
Another way is to use the animation property of CSS. An example is given here
Try this:
Javascript
$(document).ready(function() {
$('#sub_comment').on('click', function() {
var apend_data = '<div class="data orange"><p>Hello World</p></div>';
$('#comments').append($(apend_data).hide().fadeIn(2000));
setTimeout(function() {
$("#comments .data").removeClass('orange');
}, 1000);
});
});
Css
#comments {
width: 100%;
}
.data {
padding: 15px;
border: 1px solid #000;
margin: 10px auto;
}
.orange {
background-color: orange;
}
HTML
<div id="comments">
<div class="data">
<p>
Hello World
</p>
</div>
</div>
<button id="sub_comment">
Click Me
</button>
fiddle
$(() => {
var index = 1;
$('#btnSubmit').on('click', () => {
$("#conteiner").append('<p id="_' + index + '" style="display:none;width:50%" class="backColor"> ' + $('#txtComment').val() + ' </p>');
var id = "#_" + index + "";
$(id).fadeIn();
index++;
setInterval(function () {
$(id).removeClass('backColor');
}, 1000);
});
});
.backColor {
background-color:red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.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" />
</head>
<body>
<div class='row' id='conteiner' style="padding-left:50px">
</div>
<br />
<div class='row' style='width:50%;padding-left:50px'>
<form>
<div class="form-group">
<input type="text" class="form-control" id="txtComment" placeholder="comment">
</div>
<button type="button" class="btn btn-default" id='btnSubmit'>Submit</button>
</form>
</div>
</body>
</html>
Your code:
$('#comments').append($(data).hide().fadeIn(2000));
cannot work because data is text. You have to make something like
$('#comments').append(data).hide().fadeIn(2000);
but this will always hide all comments and show them again. A workaround is to put the new comment to a new container and only handle this one:
var comments = $('#comments').append('<div>' + data + '</div>');
$('div',comments).css('background-color','');
var newcom = $('div:last-child',comments);
newcom.hide().css('background-color','#ffff00').fadeIn(2000);
With the newcom object you can do any css transition or other things.

Node Jquery load pages into div error

// Userlist data array for filling in info box
var userListData = [];
// DOM Ready =============================================================
$(document).ready(function() {
// Populate the user table on initial page load
populateTable();
// Username link click
$('#userList table tbody').on('click', 'td a.linkshowuser', showUserInfo);
// Add User button click
$('#btnAddUser').on('click', addUser);
// Delete User link click
$('#userList table tbody').on('click', 'td a.linkdeleteuser', deleteUser);
//Set Default page to Home.html
$('#content').load('views/home.html');
//Call navBar function
navBar();
projectBtn();
});
// Functions =============================================================
//Navbar function
function navBar() {
$('ul#navtest li a').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
function projectBtn() {
$('a.projectbutton').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
// Fill table with data
function populateTable() {
// Empty content string
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON( '/users/userlist', function( data ) {
// Stick our user data array into a userlist variable in the global object
userListData = data;
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function(){
tableContent += '<tr>';
tableContent += '<td>' + this.username + '</td>';
tableContent += '<td>' + this.email + '</td>';
tableContent += '<td>delete</td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#userList table tbody').html(tableContent);
});
};
// Show User Info
function showUserInfo(event) {
// Prevent Link from Firing
event.preventDefault();
// Retrieve username from link rel attribute
var thisUserName = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = userListData.map(function(arrayItem) { return arrayItem.username; }).indexOf(thisUserName);
// Get our User Object
var thisUserObject = userListData[arrayPosition];
//Populate Info Box
$('#userInfoName').text(thisUserObject.fullname);
$('#userInfoAge').text(thisUserObject.age);
$('#userInfoGender').text(thisUserObject.gender);
$('#userInfoLocation').text(thisUserObject.location);
};
// Add User
function addUser(event) {
event.preventDefault();
// Super basic validation - increase errorCount variable if any fields are blank
var errorCount = 0;
$('#addUser input').each(function(index, val) {
if($(this).val() === '') { errorCount++; }
});
// Check and make sure errorCount's still at zero
if(errorCount === 0) {
// If it is, compile all user info into one object
var newUser = {
'username': $('#addUser fieldset input#inputUserName').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'age': $('#addUser fieldset input#inputUserAge').val(),
'location': $('#addUser fieldset input#inputUserLocation').val(),
'gender': $('#addUser fieldset input#inputUserGender').val()
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
// Clear the form inputs
$('#addUser fieldset input').val('');
// Update the table
populateTable();
}
else {
// If something goes wrong, alert the error message that our service returned
alert('Error: ' + response.msg);
}
});
}
else {
// If errorCount is more than 0, error out
alert('Please fill in all fields');
return false;
}
};
// Delete User
function deleteUser(event) {
event.preventDefault();
// Pop up a confirmation dialog
var confirmation = confirm('Are you sure you want to delete this user?');
// Check and make sure the user confirmed
if (confirmation === true) {
// If they did, do our delete
$.ajax({
type: 'DELETE',
url: '/users/deleteuser/' + $(this).attr('rel')
}).done(function( response ) {
// Check for a successful (blank) response
if (response.msg === '') {
}
else {
alert('Error: ' + response.msg);
}
// Update the table
populateTable();
});
}
else {
// If they said no to the confirm, do nothing
return false;
}
};
.border {
border: 4px solid black; }
.back2 {
background-color: #232323; }
.marginleft {
margin-left: 8%; }
.margin {
margin-right: 4%;
margin-left: 4%;
margin-top: 2%;
margin-bottom: 2%; }
.padding {
padding: 1%; }
.margintop {
margin-top: 1%; }
.margintop2 {
margin-top: 5%; }
.iconmargintop {
margin-top: 50px; }
.fill {
height: 100%;
width: 100%; }
p {
color: #ffffff; }
label {
color: #ffffff; }
h1 {
color: #ffffff; }
h2 {
color: #ffffff; }
th {
color: #ffffff; }
span {
color: #ffffff; }
h3 {
color: #ffffff; }
.projectseltext {
padding: 1%;
margin: 1%; }
.background {
background-color: #333333;
position: relative;
height: 100%; }
#blacktext {
color: black; }
.disablelink {
pointer-events: none;
cursor: default; }
.nav {
background-color: #b2b2b2; }
.nav a {
color: #ffffff;
font-size: 11px;
font-weight: bold;
padding: 14px 10px;
text-transform: uppercase; }
.nav li {
display: inline; }
.back1 {
background-color: #0c0c0c; }
.fit {
height: 100%;
width: 100%; }
.well {
background-color: #333333; }
.backg1 {
background-color: #333333; }
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="project">
<div class="container-fluid row">
<a href="#" title="projectnew" class="projectbutton">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin col-md-3" style="width:150px;" />
<h1 class="margin" style="margin-top:75px;">New Projects</h1>
</div>
</a>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<link rel="stylesheet" href="stylesheets/bootstrap.min.css" />
<link rel="stylesheet" href="stylesheets/main.css" />
<script src="build/js/jquery-2.2.4.min.js"></script>
<script src="build/js/bootstrap.min.js"></script>
<script src="build/js/global.js"></script>
<title></title>
</head>
<body class="background">
<div class="container-fluid nav navbar-inverse">
<ul id="navtest" class="margintop">
<li>
Home
</li>
<li>
Projects
</li>
<li>
Contact
</li>
<li>
Resume
</li>
<li>
About
</li>
<li>
Database
</li>
</ul>
</div>
<div id='content' class="tab-content" />
</body>
</html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="projectnew">
<div class="row">
<div class="container col-md-12 margintop marginleft">
Back
</div>
<div class="container-fluid margin">
<a href="" data-toggle="tab">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin" style="width:150px" />
<h1 class="margin">Comming soon.</h1>
</div>
</a>
</div>
</div>
</div>
</body>
</html>
This file is temporary, i know the contents wont do anything.
The function navBar works perfectly, however when trying to apply the same method to another class and div it seems to fail.
Whenever i click on the projectbutton class it redirects to error.html. For some reason the javascript is not seeing/handling the class on click and the href being an unsupported type redirects me to error.html. However i'm not sure what is wrong with my code.
welcome;
In your HTML code, <a href="projectnew" class="projectbutton"> you have an href for your a element, if you click on this, it will go to the page "www.yourdomain.com/projectnew" since this page does not exist, you will be redirected to your error page...
To solve this problem, you should use preventDefault, in order to prevent your link element to operate things that you do not want.
$('a.projectbutton').click(function(event) {
event.preventDefault();
var page = $(this).attr('href');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
I did not try it out, but it should work.
Read more about preventDefault: https://api.jquery.com/event.preventdefault/
OR;
Since the main problem is your href attributes in your a elements, try to remove them;
Home
Use title as your specifier in your JS;
$('a.projectbutton').click(function() {
var page = $(this).attr('title'); //changed this into title.
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});

How to wrap div element around newly typed text so that associated css result will be shown in real time

I have created a simple text editor which shows the associated CSS results in real time. for example if a user clicks Bold Then text becomes bold while user is typing (it shows real time change). Same like this I want a button after click it will wrap the new text with a div tag with specified class or id.
I know wrap method can wrap the div or other tag. But after adding new div tags through wrap() I want store its result which contains newly added div tags. so that I can use those result to generate new html pages.
Here is the html code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="texteditor.js"></script>
</head>
<body>
<div id="content" style="margin-top: 10px; height: 70%; text-align: center;">
<h2><u>Simple Text Editor Created Using jQuery</u></h2>
<div class="ze ie"></div>
<style>
.font-bold.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
.selected {
background-color: orange;
}
#openpb {
margin: 15px;
}
</style>
<button type="button" class="g-button g-button-submit" id='stext'>Text</button>
<button type="button" class="g-button g-button-submit" id='shtml'>HTML</button>
<div id="controls" style="margin-bottom: 10px;">
<a id="bold" style="color: black; display: inline-block;" class="font-bold">
<button type="button">B</button>
</a>
<a id="italic" style="color: black !important; display: inline-block;" class="italic">
<button type="button">I</button>
</a>
<a id="link" class="link" style="display: inline-block;">
<button type="button">Link</button>
</a>
<select id="fonts" class="g-button">
<option value="Normal">Normal</option>
<option value="Arial">Arial</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="Courier New">Courier New</option>
<option value="Monotype Corsiva">Monotype</option>
<option value="Tahoma New">Tahoma</option>
<option value="Times">Times</option>
<option value="Trebuchet New">Trebuchet</option>
<option value="Ubuntu">Ubuntu</option>
</select>
</div>
<iframe frameborder="0" id="textEditor" style="width: 500px; height: 80px; border: 2px solid #CCC; border-radius: 20px; overflow: auto;"></iframe>
<textarea name="text" id='text' style="border-radius: 20px; overflow: auto; display: none; padding-left: 10px;" rows="6" cols="53"></textarea>
</div>
</body>
</html>
here is Jquery: as you can I have used setinterval method to show result in real time in textarea. same like this I want a button which will wrap new or selected text with div tag with specified id and class and I want store this changes(newly added div tag) in textarea.
$(document).ready(function () {
document.getElementById('textEditor').contentWindow.document.designMode = "on";
document.getElementById('textEditor').contentWindow.document.close();
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
$("#bold").click(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
boldIt();
});
$("#italic").click(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
ItalicIt();
});
$("#fonts").on('change', function () {
changeFont($("#fonts").val());
});
$("#link").click(function () {
var urlp = prompt("What is the link:", "http://");
url(urlp);
});
$("#stext").click(function () {
$("#text").hide();
$("#textEditor").show();
$("#controls").show()
});
$("#shtml").on('click', function () {
$("#text").css("display", "block");
$("#textEditor").hide();
$("#controls").hide();
});
});
function boldIt() {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("bold", false, "");
edit.focus();
}
function ItalicIt() {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("italic", false, "");
edit.focus();
}
function changeFont(font) {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("FontName", false, font);
edit.focus();
}
function url(url) {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("Createlink", false, url);
edit.focus();
}
setInterval(function () {
var gyt = $("#textEditor").contents().find("body").html().match(/#/g);
if ($("#textEditor").contents().find("body").html().match(/#/g) >= 0) { } else {
$("#text").val($("#textEditor").contents().find("body").html());
}
$("#text").val($("#textEditor").contents().find("body").html());
}, 1000);
I don't want use third party text editor plugins. in short I want texteditor which contain a button, after clicking this button it will wrap new text with div tag with specified class or id. something like Stack Overflow text editor...with facility of adding custom div with specified class or id.
<html>
<head>
<style>
#Problem{margin: 5px; outline: 1px dotted red; padding: 5px}
#Solution{margin: 5px; outline: 1px dotted green; padding: 5px}
#Solution textarea{
height: 200px;
width: 500px;
}
</style>
<script>
//Wraps the text in a new div with optional id and classname.
//Returns the new div.
function wrapMe(text, id, classname){
var tE = null;
if (text && text.trim() != ''){
tE = document.createElement('div');
tE.id = (id || '');
tE.className = (classname || '');
tE.innerHTML = (text || '');
}
return tE
}
//Adds the outer html of passed element to the textarea with a linebreak
function addElementToTextarea(e){
var tA = document.querySelector('textarea');
if (tA && e){
tA.innerHTML = (tA.innerHTML || '') + e.outerHTML + '
&#010'
}
}
</script>
</head>
<body>
<div id = 'Problem'>
Problem: I don't want use third party text editor plugins. in short i want texteditor which contain a button, after clicking this button it will wrap new text with div tag with specified class or id. something like stackover flow text editor...with facility of adding custom div with speicifed class or id.
</div>
<div id = 'Solution'>
<input type = 'text' />
<button onclick = "addElementToTextarea(wrapMe(this.parentNode.querySelector('input').value, 'testid', 'testclass'))">Wrap me</button>
<br /><br />
<textarea readonly = 'readonly'></textarea>
</div>
</body>
</html>

Custom "confirm" dialog in JavaScript?

I've been working on an ASP.net project that uses custom 'modal dialogs'. I use scare quotes here because I understand that the 'modal dialog' is simply a div in my html document that is set to appear "on top" of the rest of the document and is not a modal dialog in the true sense of the word.
In many parts of the web site, I have code that looks like this:
var warning = 'Are you sure you want to do this?';
if (confirm(warning)) {
// Do something
}
else {
// Do something else
}
This is okay, but it would be nice to make the confirm dialog match the style of the rest of the page.
However, since it is not a true modal dialog, I think that I need to write something like this: (I use jQuery-UI in this example)
<div id='modal_dialog'>
<div class='title'>
</div>
<input type='button' value='yes' id='btnYes' />
<input type='button' value='no' id='btnNo' />
</div>
<script>
function DoSomethingDangerous() {
var warning = 'Are you sure you want to do this?';
$('.title').html(warning);
var dialog = $('#modal_dialog').dialog();
function Yes() {
dialog.dialog('close');
// Do something
}
function No() {
dialog.dialog('close');
// Do something else
}
$('#btnYes').click(Yes);
$('#btnNo').click(No);
}
Is this a good way to accomplish what I want, or is there a better way?
You might want to consider abstracting it out into a function like this:
function dialog(message, yesCallback, noCallback) {
$('.title').html(message);
var dialog = $('#modal_dialog').dialog();
$('#btnYes').click(function() {
dialog.dialog('close');
yesCallback();
});
$('#btnNo').click(function() {
dialog.dialog('close');
noCallback();
});
}
You can then use it like this:
dialog('Are you sure you want to do this?',
function() {
// Do something
},
function() {
// Do something else
}
);
SweetAlert
You should take a look at SweetAlert as an option to save some work. It's beautiful from the default state and is highly customizable.
Confirm Example
sweetAlert(
{
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!"
},
deleteIt()
);
To enable you to use the confirm box like the normal confirm dialog, I would use Promises which will enable you to await on the result of the outcome and then act on this, rather than having to use callbacks.
This will allow you to follow the same pattern you have in other parts of your code with code such as...
const confirm = await ui.confirm('Are you sure you want to do this?');
if(confirm){
alert('yes clicked');
} else{
alert('no clicked');
}
See codepen for example, or run the snippet below.
https://codepen.io/larnott/pen/rNNQoNp
const ui = {
confirm: async (message) => createConfirm(message)
}
const createConfirm = (message) => {
return new Promise((complete, failed)=>{
$('#confirmMessage').text(message)
$('#confirmYes').off('click');
$('#confirmNo').off('click');
$('#confirmYes').on('click', ()=> { $('.confirm').hide(); complete(true); });
$('#confirmNo').on('click', ()=> { $('.confirm').hide(); complete(false); });
$('.confirm').show();
});
}
const saveForm = async () => {
const confirm = await ui.confirm('Are you sure you want to do this?');
if(confirm){
alert('yes clicked');
} else{
alert('no clicked');
}
}
body {
margin: 0px;
font-family: "Arial";
}
.example {
padding: 20px;
}
input[type=button] {
padding: 5px 10px;
margin: 10px 5px;
border-radius: 5px;
cursor: pointer;
background: #ddd;
border: 1px solid #ccc;
}
input[type=button]:hover {
background: #ccc;
}
.confirm {
display: none;
}
.confirm > div:first-of-type {
position: fixed;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
top: 0px;
left: 0px;
}
.confirm > div:last-of-type {
padding: 10px 20px;
background: white;
position: absolute;
width: auto;
height: auto;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
border-radius: 5px;
border: 1px solid #333;
}
.confirm > div:last-of-type div:first-of-type {
min-width: 150px;
padding: 10px;
}
.confirm > div:last-of-type div:last-of-type {
text-align: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="example">
<input type="button" onclick="saveForm()" value="Save" />
</div>
<!-- Hidden confirm markup somewhere at the bottom of page -->
<div class="confirm">
<div></div>
<div>
<div id="confirmMessage"></div>
<div>
<input id="confirmYes" type="button" value="Yes" />
<input id="confirmNo" type="button" value="No" />
</div>
</div>
</div>
I would use the example given on jQuery UI's site as a template:
$( "#modal_dialog" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Yes": function() {
$( this ).dialog( "close" );
},
"No": function() {
$( this ).dialog( "close" );
}
}
});
var confirmBox = '<div class="modal fade confirm-modal">' +
'<div class="modal-dialog modal-sm" role="document">' +
'<div class="modal-content">' +
'<button type="button" class="close m-4 c-pointer" data-dismiss="modal" aria-label="Close">' +
'<span aria-hidden="true">×</span>' +
'</button>' +
'<div class="modal-body pb-5"></div>' +
'<div class="modal-footer pt-3 pb-3">' +
'OK' +
'<button type="button" class="btn btn-secondary abortBtn btn-sm" data-dismiss="modal">Abbrechen</button>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
var dialog = function(el, text, trueCallback, abortCallback) {
el.click(function(e) {
var thisConfirm = $(confirmBox).clone();
thisConfirm.find('.modal-body').text(text);
e.preventDefault();
$('body').append(thisConfirm);
$(thisConfirm).modal('show');
if (abortCallback) {
$(thisConfirm).find('.abortBtn').click(function(e) {
e.preventDefault();
abortCallback();
$(thisConfirm).modal('hide');
});
}
if (trueCallback) {
$(thisConfirm).find('.yesBtn').click(function(e) {
e.preventDefault();
trueCallback();
$(thisConfirm).modal('hide');
});
} else {
if (el.prop('nodeName') == 'A') {
$(thisConfirm).find('.yesBtn').attr('href', el.attr('href'));
}
if (el.attr('type') == 'submit') {
$(thisConfirm).find('.yesBtn').click(function(e) {
e.preventDefault();
el.off().click();
});
}
}
$(thisConfirm).on('hidden.bs.modal', function(e) {
$(this).remove();
});
});
}
// custom confirm
$(function() {
$('[data-confirm]').each(function() {
dialog($(this), $(this).attr('data-confirm'));
});
dialog($('#customCallback'), "dialog with custom callback", function() {
alert("hi there");
});
});
.test {
display:block;
padding: 5p 10px;
background:orange;
color:white;
border-radius:4px;
margin:0;
border:0;
width:150px;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.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.min.css" rel="stylesheet"/>
example 1
<a class="test" href="http://example" data-confirm="do you want really leave the website?">leave website</a><br><br>
example 2
<form action="">
<button class="test" type="submit" data-confirm="send form to delete some files?">delete some files</button>
</form><br><br>
example 3
<span class="test" id="customCallback">with callback</span>
One other way would be using colorbox
function createConfirm(message, okHandler) {
var confirm = '<p id="confirmMessage">'+message+'</p><div class="clearfix dropbig">'+
'<input type="button" id="confirmYes" class="alignleft ui-button ui-widget ui-state-default" value="Yes" />' +
'<input type="button" id="confirmNo" class="ui-button ui-widget ui-state-default" value="No" /></div>';
$.fn.colorbox({html:confirm,
onComplete: function(){
$("#confirmYes").click(function(){
okHandler();
$.fn.colorbox.close();
});
$("#confirmNo").click(function(){
$.fn.colorbox.close();
});
}});
}
Faced with the same problem, I was able to solve it using only vanilla JS, but in an ugly way. To be more accurate, in a non-procedural way. I removed all my function parameters and return values and replaced them with global variables, and now the functions only serve as containers for lines of code - they're no longer logical units.
In my case, I also had the added complication of needing many confirmations (as a parser works through a text). My solution was to put everything up to the first confirmation in a JS function that ends by painting my custom popup on the screen, and then terminating.
Then the buttons in my popup call another function that uses the answer and then continues working (parsing) as usual up to the next confirmation, when it again paints the screen and then terminates. This second function is called as often as needed.
Both functions also recognize when the work is done - they do a little cleanup and then finish for good. The result is that I have complete control of the popups; the price I paid is in elegance.
I managed to find the solution that will allow you to do this using default confirm() with minimum of changes if you have a lot of confirm() actions through out you code. This example uses jQuery and Bootstrap but the same thing can be accomplished using other libraries as well. You can just copy paste this and it should work right away
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Project Title</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!--[if lt IE 9]>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<h1>Custom Confirm</h1>
<button id="action"> Action </button>
<button class='another-one'> Another </button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript">
document.body.innerHTML += `<div class="modal fade" style="top:20vh" id="customDialog" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" id='dialog-cancel' class="btn btn-secondary">Cancel</button>
<button type="button" id='dialog-ok' class="btn btn-primary">Ok</button>
</div>
</div>
</div>
</div>`;
function showModal(text) {
$('#customDialog .modal-body').html(text);
$('#customDialog').modal('show');
}
function startInterval(element) {
interval = setInterval(function(){
if ( window.isConfirmed != null ) {
window.confirm = function() {
return window.isConfirmed;
}
elConfrimInit.trigger('click');
clearInterval(interval);
window.isConfirmed = null;
window.confirm = function(text) {
showModal(text);
startInterval();
}
}
}, 500);
}
window.isConfirmed = null;
window.confirm = function(text,elem = null) {
elConfrimInit = elem;
showModal(text);
startInterval();
}
$(document).on('click','#dialog-ok', function(){
isConfirmed = true;
$('#customDialog').modal('hide');
});
$(document).on('click','#dialog-cancel', function(){
isConfirmed = false;
$('#customDialog').modal('hide');
});
$('#action').on('click', function(e) {
if ( confirm('Are you sure?',$(this)) ) {
alert('confrmed');
}
else {
alert('not confimed');
}
});
$('.another-one').on('click', function(e) {
if ( confirm('Are really, really, really sure ? you sure?',$(this)) ) {
alert('confirmed');
}
else {
alert('not confimed');
}
});
</script>
</body>
</html>
This is the whole example. After you implement it you will be able to use it like this:
if ( confirm('Are you sure?',$(this)) )
I created a js file with below given code and named it newconfirm.js
function confirm(q,yes){
var elem='<div class="modal fade" id="confirmmodal" role="dialog" style="z-index: 1500;">';
elem+='<div class="modal-dialog" style="width: 25vw;">';
elem+='<div class="modal-content">';
elem+='<div class="modal-header" style="padding:8px;background-color:lavender;">';
elem+='<button type="button" class="close" data-dismiss="modal">×</button>';
elem+='<h3 class="modal-title" style="color:black;">Message</h3></div>';
elem+='<div class="modal-body col-xs-12" style="padding:;background-color: ghostwhite;height:auto;">';
elem+='<div class="col-xs-3 pull-left" style="margin-top: 0px;">';
elem+='<img class="img-rounded" src="msgimage.jpg" style="width: 49%;object-fit: contain;" /></div><div class="col-xs-9 pull-left "><p class="aconfdiv"></p></div></div>';
elem+='<div class="modal-footer col-xs-12" style="padding:6px;background-color:lavender;"><div class="btn btn-sm btn-success yes pull-left">Yes</div><button type="button" class="btn btn-default btn-sm" data-dismiss="modal">No</button></div></div></div></div>';
$('body').append(elem);
$('body').append('<div class="lead cresp"></div>');
$('.aconfdiv').html(q);
$('#confirmmodal').modal('show');
$('.yes').on('click',function(){
$('body').find('.cresp').html('Yes');
$('#confirmmodal').modal('hide');
yes();
})
}
and in my main php file calling confirm in the javascript like this
$('.cnf').off().on('click',function(){
confirm("Do you want to save the data to Database?<br />Kindly check the data properly as You cannot undo this action",function(){
var resp=$('body').find('.cresp').html();
$('body').find('.cresp').remove();
if(resp=='Yes'){
alert("You clicked on Yes Bro.....")
}
});
})

Categories

Resources