Materialize modal dynamically - javascript

I want to create modal in materialize dynamically.
this is my javascript code:
$(document).ready(function(){
var modalContainer = $('<div id="modal_id" class="modal"></div>');
var modalContent = $('<div class="modal-content"><p>my content</p></div>');
modalContainer.append(modalContent);
modalContainer.modal(); // or modalContainer.modal('open');
});
and this is my trigger button:
<a class="waves-effect waves-light btn modal-trigger" href="#modal_id">Show Modal</a>
but, this is not working. when i click to Show Modal anchor, show me the wrapper of modal and do not show modal box.
please help me. thanks.

You can do it with this simple approach. Create and an empty div with .modal class and whatever the id you want to assign.
Then in jQuery, create a variable and save a div with class modal-content. In that div specify your message or content, you want to add dynamically. After that, append that variable to modal using $(.modal).append() and open your modal using .modal()
Take a look at Example
I've created a jsfiddle take a look at it.
Demo - jsFiddle
Example
HTML
<a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal</a>
<div id="modal1" class="modal"></div>
jQuery
$(document).ready(function(){
// Here specify your content or message, enclose between <p>
var content = '<div class="modal-content"><p>my content</p></div>';
$('.modal').append(content);
$('.modal').modal();
});

You can open the modal on 1.0.0 using pure javascript like this
const elem = document.getElementById('modalId here');
const instance = M.Modal.init(elem, {dismissible: false});
instance.open();

I wrote a small class to create modals dynamically. Note that setting the height and width is a bit buggy, I don't really know why. I only need fixed-footer modals in my application, but that class could easily be set dynamically to fit your needs. Anyways, I hope it helps:
class Modal {
constructor(opt) {
this.name = opt.name;
this.width = opt.width || '';
this.height = opt.height || '';
this.topMargin = opt.height ? Math.floor((100 - this.height) / 2) : '';
this.style = (opt.width && opt.height) ? 'width: ' + this.width + '%; height: ' + this.height + 'vh; top: ' + this.topMargin + 'vh;' : opt.width ? 'width: ' + this.width + '%;' : opt.height ? 'height: ' + this.height + 'vh; top: ' + this.topMargin + 'vh' : '';
this.footerButtons = opt.footerButtons || '';
this.openButton = opt.openButton || null;
this.title = opt.title || '';
this.onOpen = opt.onOpen;
this.fixedContent = opt.fixedContent || '';
this.template = '<div id="' + this.name + '" class="modal modal-fixed-footer" style="' + this.style + '"><div class="modal-content" style="padding-top: 17px;"><h4>' + this.title + '</h4><div class="divider"></div><br>' + this.fixedContent + '<div class="modal-content-dynamic"></div></div><div class="modal-footer">' + this.footerButtons + '</div></div>';
$('.container').append(this.template);
var self = this;
if (this.openButton) {
$(document).on('click', this.openButton, function () {
self.open();
});
}
}
open() {
$('#' + this.name).openModal({
dismissable: false,
preventScrolling: false
});
if (this.onOpen) this.onOpen(this);
}
close() {
$('#' + this.name).closeModal();
}
setContent(content) {
$('#' + this.name).find('.modal-content-dynamic').html(content);
}
addContent(content) {
$('#' + this.name).find('.modal-content-dynamic').append(content);
}
setTitle(title) {
$('#' + this.name).find('.modal-content h4').html(title);
}
setFooterButtons(buttons) {
$('#' + this.name).find('.modal-footer').html(buttons);
}
}
And then use it like this:
var testModal = new Modal({
name: 'testModal',
openButton: '#open_testModal',
title: '<b>TestModal</b>',
fixedContent: '<p>Some static content</p>',
onOpen: function (modal) {
// do something every time the modal is opened
}
});

Related

How to update div content by changing panel name

When I edit panels name I want to update div content, that will have tab-pane name.
I tried to get the value and change it "onchange", but
I think I did something incorrectly.
http://jsfiddle.net/agata666/5zLmtqby/139/
var $foo = $(".tab-pane");
var $newPanelDefault = $foo.clone();
var hash = 1;
$(".add").on("click", function() {
var $newPanel = $newPanelDefault.clone();
var hashClass = 'zone-panel-' + generateHash();
$newPanel.find(".panel").data('hash', hashClass).attr("href", "#" + (++hash)).text("Zone " + hash);
$newPanel.attr("id", "tab" + hashClass);
var nextTab = $('.tabs li').size()+1;
$('<li class="' + hashClass + '">Zone ' + hash + ' <i class="fas fa-pencil-alt pencil"></i></li>').appendTo('.tabs');
$($newPanel).appendTo('.tab-content');
$(".pencil").click(function() {
$(".nav-tabs li.active").attr('contenteditable',$(".nav-tabs li.active").attr('contenteditable')==='true'?'false':'true' );
});
});
var panelDefault = document.querySelectorAll('.panel-default');
var exTabFirst = document.querySelectorAll('.exTabFirst');
var exTabSecond = document.querySelectorAll('.exTabSecond');
var addZoneButton = document.getElementById('add');
function generateHash() {
return Math.random().toString(16).substr(-5);
}
addZoneButton.addEventListener('click', function () {
var randomNumber = generateHash();
panelDefault.innerHTML = 'panel panel-default foo template ' + randomNumber;
exTabFirst.innerHTML = 'exTabFirst ' + randomNumber;
exTabSecond.innerHTML = 'exTabSecond ' + randomNumber;
});
$(".pencil").click(function() {
$(".nav-tabs li.active").attr('contenteditable',$(".nav-tabs li.active").attr('contenteditable')==='true'?'false':'true' );
});
Could you help me?

jQuery function conversion

I've been working on this script that I am using with a WordPress plugin I wrote for our blogs at work. I'm stripping it down to make it a pure jQuery plugin but most of the questions I've seen where for getting the plugin to work like this:
$('.some-target').cta();
Whereas I want to write it so that the user can do something like:
cta();
or
$.cta
I'm not really getting clear answers or seeing many guides covering this, or really if it's possible. In the end I want it to work like it's original iteration for WP, but as a stand alone jQuery plugin for static sites:
cta({
text: "Some Text",
icon: "Some-icon.jpg",
dist: 50
});
Here is the original code:
jQuery(document).ready(function($){
cta = function(o) {
o = o || {};
var bgColor = o.bgColor;
var url = o.url;
var text = o.text;
var icon = o.icon;
var buttonText = o.buttonText;
var target = o.target;
var dist = o.dist;
if((o.icon != null) || o.icon == "" ) {
jQuery('body').append(
'<div class="cta-popup-wrapper with-icon"><div class="cta-popup"><span class="close-trigger">X</span><img class="cta-icon" src="' + icon + '" alt="Call to Action Icon"><p>' + text + '</p><a class="cta-button" style="background-color:' + bgColor + ';" href="' + url + '">' + buttonText + '</a></div></div>'
);
} else {
jQuery('body').append(
'<div class="cta-popup-wrapper without-icon"><div class="cta-popup"><span class="close-trigger">X</span><p>' + text + '</p><a class="cta-button" style="background-color:' + bgColor + ';" href="' + url + '">' + buttonText + '</a></div></div>'
);
}
if(target != null) {
var t = $(target);
if(t.length) {
$(window).scroll(function() {
var hT = t.offset().top,
hH = t.outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
$('.cta-popup-wrapper').addClass('shown');
} else {
$('.cta-popup-wrapper').removeClass('shown');
}
});
}
} else {
if((dist != null) && (dist > 0)) {
var b = $('body').innerHeight();
dist = dist / 100;
var trigger = b * dist;
$(window).scroll(function() {
var wS = $(this).scrollTop();
if (wS > trigger){
$('.cta-popup-wrapper').addClass('shown');
} else {
$('.cta-popup-wrapper').removeClass('shown');
}
});
}
}
}
});

How to retrieve function input javascript

I've got the following code that produces a dynamically created image button and panel in asp.net: -
Panel panBlocks = new Panel();
panBlocks.ID = "PanBlockQuestionID" + recordcount.ToString();
panBlocks.Width = 1300;
panBlocks.Height = 50;
panBlocks.BackColor = Color.Pink;
ImageButton cmdBlocks = new ImageButton();
cmdBlocks.ImageUrl = "~/Images/block3.png";
cmdBlocks.ID = "lblImg" + recordcount.ToString();
cmdBlocks.Attributes["class"] = "liQuestionsLabel2";
cmdBlocks.Width = 30;
cmdBlocks.Attributes.Add("OnMouseOver", "showPanel(" + "CPH_Body_" + panBlocks.ClientID.ToString() + ")");
cmdBlocks.Attributes.Add("OnMouseOut", "hidePanel();");
li.Controls.Add(cmdBlocks);
li.Controls.Add(panBlocks);
When I hover over the image I want it to display a particular panel. I've added the "CPH_Body_" + panBlocks.ClientID.ToString() as an attribute.
I've got the following javascript code:
function showPanel(PanelID)
{
document.getElementById("CPH_Body_liQuestions1").style.height = "40px";
}
How do I retrieve the PanelID in the javascript please as it looks like an array. I need to retrieve this so I know which panel to display please.
IIUC (!!):
Change this :
cmdBlocks.Attributes.Add("OnMouseOver", "showPanel(" + "CPH_Body_" + panBlocks.ClientID.ToString() + ")");
To:
cmdBlocks.Attributes.Add("OnMouseOver", "showPanel('" + panBlocks.ClientID.ToString() + "')");
And change this :
function showPanel(PanelID)
{
document.getElementById("CPH_Body_liQuestions1").style.height = "40px";
}
To
function showPanel(PanelID)
{
document.getElementById(PanelID).style.height = "40px";
}

Error in Dynamics CRM Custom form Event Javascript

I am trying to make a button on a form in Dynamics CRM, so that onClick the button show a dialog. The JS code I am using is as follows:
function addButton(attributename) {
if (document.getElementById(attributename) != null) {
var sFieldID = "field" + attributename;
var elementID = document.getElementById(attributename + "_d");
var div = document.createElement("div");
div.style.width = "19%";
div.style.textAlign = "right";
div.style.display = "inline";
elementID.appendChild(div, elementID);
div.innerHTML = '<button id="' + sFieldID + '" type="button" style="margin-left: 4px; width: 100%;" ><img src="/_imgs/ico_16_4210.gif" border="0" alt="Dial this number"/></button>';
document.getElementById(attributename).style.width = "80%";
document.getElementById(sFieldID).onclick = function () {onbuttonclick(); };
}
}
function onbuttonclick() { alert('Hi');}
This function is written in a JS Web Resource which gets triggered with form onload event of contact entity. Whenever the form load event is triggered I get the following error in a dialog box:
There was an error with this field's customized event.
Field:window
Event:onload
Error:undefined
kindly guide me towards the resolution.
The code is taken from a sample example.
This simply means that you have an error somewhere in your JavaScript.
A much better solution would be to use a ribbon button, and have that ribbon button call javascript, instead of messing with the DOM (which is unsupported). drop the following code into your ribbondiffxml:
<Actions>
<JavaScriptFunction Library="$[js library name]" FunctionName="[js function name]" />
</Actions>
Specifically, this should go into the CommandDefinitionNode.
Here is an example of what I do to open a dialog via javascript:
Ribbon.openDialogProcess = function (dialogId, EntityName, objectId) {
var url = Xrm.Page.context.getClientUrl() +
"/cs/dialog/rundialog.aspx?DialogId=" +
dialogId + "&EntityName=" +
EntityName + "&ObjectId=" +
objectId;
var width = 400;
var height = 400;
var left = (screen.width - width) / 2;
var top = (screen.height - height) / 2;
window.open(url, '', 'location=0,menubar=1,resizable=0,width=' + width + ',height=' + height + ',top=' + top + ',left=' + left + '');
}
so simply call that method in the RibbonDiffXML.

js bb codes duplicate action error

just made my own bbcodes plugin for textarea
but i wasn`t able to correct the error..
If the page uses 2 textareas, in 1st one actions are dublicated twice.
If the page uses 1 textarea, everything is ok.
How to fix it?
code:
/*
* plugin: bbcodes based on jquery.bbcode.js
* version: 0.2
*
* author: atomos
* site: http://light-engine.ru
*/
(function($){
$.fn.bbcode = function(options){
var options = $.extend({
tag_bold: true,
tag_italic: true,
tag_right: true,
tag_center: true,
tag_left: true,
tag_link: true,
tag_image: true,
image_url: 'bbimage/'
}, options||{});
var taid = $(this).attr('name');
var text = '<div class="btn-group">';
if(options.tag_bold)
{
text = text + '<a class="btn" title="Жирный" href="#" id="b"><i class="icon-bold"></i></a>';
}
if(options.tag_italic)
{
text = text + '<a class="btn" title="Курсив" href="#" id="i"><i class="icon-italic"></i></a>';
}
text = text + '</div><div class="btn-group">';
if(options.tag_right)
{
text = text + '<a class="btn" title="Направо" href="#" id="right"><i class="icon-align-right"></i></a>';
}
if(options.tag_center)
{
text = text + '<a class="btn" title="Центр" href="#" id="center"><i class="icon-align-center"></i></a>';
}
if(options.tag_left)
{
text = text + '<a class="btn" title="Налево" href="#" id="left"><i class="icon-align-left"></i></a>';
}
text = text + '</div><div class="btn-group">';
if(options.tag_link)
{
text = text + '<a class="btn" title="Ссылка" href="#" id="url"><i class="icon-share-alt"></i></a>';
}
if(options.tag_image)
{
text = text + '<a class="btn" title="Изображение" href="#" id="img"><i class="icon-picture"></i></a>';
}
text = text + '</div>';
$(this).wrap('<div id="bbcode-' + taid + '"></div>');
$('#bbcode-' + taid).prepend('<div class="btn-toolbar">' + text + '</div>');
$('.controls a[class=btn]').click(function()
{
var id = $(this).parent('.btn-group').parent('.btn-toolbar').parent().attr('id');
var area = $('textarea[name=' + id.substring(7) + ']').get(0);
var button_id = $(this).attr('id');
var param = '';
var start = '[' + button_id + ']';
var end = '[/' + button_id + ']';
if (button_id == 'img')
{
param = prompt('Введите адрес картинки:', 'http://');
if (param && param != 'http://') start += param;
else return false;
}
else if (button_id == 'url')
{
param = prompt('Введите адрес ссылки:', 'http://');
if (param && param != 'http://') start = '[url href=' + param + ']';
else return false;
}
insert(start, end, area);
return false;
});
}
function insert(start, end, element)
{
if (document.selection)
{
element.focus();
sel = document.selection.createRange();
sel.text = start + sel.text + end;
}
else if (element.selectionStart || element.selectionStart == '0')
{
element.focus();
var startPos = element.selectionStart;
var endPos = element.selectionEnd;
element.value = element.value.substring(0, startPos) + start + element.value.substring(startPos, endPos) + end + element.value.substring(endPos, element.value.length);
}
else
{
element.value += start + end;
}
}
})(jQuery);
i have demo: here
Your problem is this:
$(document).ready(function(){
$('textarea').each(function() {
$(this).bbcode();
});
});
That means that your script is going trough every textareas on the page and run bbcode() function on them.
For some reason it iterates trough the first textarea as many times as there are textareas on page.
So if you have 2 areas function will be executed 2 times on first area 1 time on second.
If you have 3 areas function will be executed 3 times on first, 2 times on second and 1 time on last one.
And so on...
I would suggest to heavily adjust your script so that you can forward an ID parameter of specific textarea that you wish to manipulate when you do an onclick event on osme of bbcode buttons like:
<textarea class="input-xxlarge" id="area_1" rows="3"></textarea>
<a onclick="$('#area_1').bbcode();" class="btn" title="Жирный" href="#" id="b"><i class="icon-bold"></i></a>
This is only a tip in which direction you should go... And also consider not doing it with jquery instead do it in pure JS it is much cleaner and on the end you will know every bit of your code. So that future maintaining of script would be fast and easy.

Categories

Resources