Native Javascript Alert - style override remove new line functionality - javascript

I am using a simple jQuery plugin to style my javascript alerts. The problem being the usual methods for adding new lines does not appear to work. Here is the javascript for the plugin, any ideas?
(function($) {
$.fn.customAlert = function(options) {
var settings = {
'alertTitle' : 'Notice!',
'alertOk' : 'OK',
'alertClose' : 'x',
'draggable' : false
};
if (options) $.extend(settings, options);
if(document.getElementById) {
window.defaultAlert = window.alert;
window.alert = function(msgTxt) {
if ($('#modalDiv').length > 0) return; // Only ever show one alert
// The modal div to block out the rest of the document whilst the alert is shown
var modalDiv = $('<div></div>');
modalDiv.attr('id', 'modalDiv');
modalDiv.height($(document).height()); // Make overlay cover the whole window
// The alert container
var alertDiv = $('<div></div>');
alertDiv.attr('id', 'alertDiv');
// The alert title
var titleH1 = $('<h1></h1>');
titleH1.addClass('titleH1');
titleH1.text(settings.alertTitle);
// The alert text to display
var msgP = $('<p></p>');
msgP.text(msgTxt);
// OK button - will remove/close the alert on click
var okBtn = $('<a></a>');
okBtn.addClass('okBtn');
okBtn.text(settings.alertOk);
okBtn.attr('href', '#');
// X button - will remove/close the alert on click
var closeBtn = $('<span></span>');
closeBtn.addClass('alert-close');
closeBtn.text(settings.alertClose);
// Append elements to document body
alertDiv.append(titleH1);
alertDiv.append(msgP);
alertDiv.append(okBtn);
alertDiv.append(closeBtn);
$('body').append(modalDiv);
$('body').append(alertDiv);
// Center alert on page
$('#alertDiv').css('top', ($(window).height()/2) - ($('#alertDiv').height()/2)+'px');
$('#alertDiv').css('left', ($(window).width()/2) - ($('#alertDiv').width()/2)+'px');
// Make draggable
if (settings.draggable && $('#alertDiv').draggable) {
$('#alertDiv').draggable({
handle: 'h1',
opacity: 0.4
});
$('#alertDiv h1').css('cursor', 'move');
}
// Bind OK button to remove/close alert
$('#alertDiv .okBtn, #alertDiv .alert-close').bind('click', function(e) {
$('#alertDiv').remove();
$('#modalDiv').remove();
e.preventDefault();
});
};
}
};
})(jQuery);
I am guessing its a case of in this above finding /n and adding a <br> or </p><p>. I am unsure how to do that if even possible though.

Change this line:
msgP.text(msgTxt);
to
msgP.html(msgTxt);
and I think then you can use <br /> and other html tags.

Related

'Close' button does not work in javascript

In the mobile version on my form appears 'Close' button.
Unfortunately, it does not work. I see a normal button, but when I click there is no reaction. In the javascript I load the file form-with-button.html to render form content in my all .html files.
<div id="form-with-button">
</div>
and use javascript to show and close.
//Onload show header and footer content
$("#header").load('header.html', function(){
$('#nav').affix({
offset: {top: $('#header').height()-$('#nav').height()}
});
});
$("#footer").load('footer.html');
$("#contact").load('footer-contact.html');
$("#form-with-button").load('form-with-button.html');
// Sticky Buttons Show Hide
$("#fix-quote, #fix-contact").on("click", function() {
var body = $("body");
var openPos= ["",""];
var id = $(this).attr("id");
var content = $("#"+id+"-content");
var property = (content.attr("class").toString().indexOf("left") > -1)? "left": "right";
if (!body.hasClass("bd_"+id)) {
openPos= [0,380]
var ele = $(this);
body.addClass("bd_"+id)
setTimeout(function(){
body.on("click.fix",function(ev) {
if($(ev.target).closest(".fixed-container").length == 0){
$(ele).click()
}
});
},10);
} else {
body.removeClass("bd_"+id).off("click.fix");
}
content.css("top","").show().css(property, openPos[0]);
$(this).css(property, openPos[1]);
});
// Mobile Requests Showhide
$("#fix-quote-mob, #fix-contact-mob").on("click", function() {
var id = $(this).attr("id").slice(0,-4);
var content = $("#"+id+"-content");
content.show()
setTimeout(function(){
content.css("top",0)
},10)
});
$(".fix-contact-close").on("click", function() {
var content = $(this).closest(".fixed-container");
content.css("top","").delay(400).hide(0);
});
Please help, why my button does not work?
You are trying to add a handler to an element created in a dynamic way, so you need to refactor your code in order to make it work:
$(document).on("click", ".fix-contact-close", function() {
var content = $(this).closest(".fixed-container");
content.css("top","").delay(400).hide(0);
});

How to execute a function when clicking an area inside an object?

I created an object with map Areas by using DOM-Elements. Now I want to execute a function when clicked on an area(coordinates). I think I also Need to check the area if it is clicked or not ? Also I think I'm missing something on the DOM-Element.
var _images = { //Object-MapArea
start: {
path: 'start.jpg',
areas: [{
coords: '18,131,113,140',
text: 'Homepage',
onclick: doSomething, // ???
}]
},
}
// ..... there is more code not shown here
//Creating DOM-Elements
var areaElem = document.createElement('AREA');
// Set attributes
areaElem.coords = area.coords;
areaElem.setAttribute('link', area.goto);
areaElem.setAttribute("title", area.text);
areaElem.setAttribute("shape", "rect");
areaElem.onclick = doSomething; ? ? ?
if (element.captureEvents) element.captureEvents(Event.CLICK); ? ? ?
areaElem.addEventListener('click', onArea_click);
_map.appendChild(areaElem);
function doSomething(e) {
if (!e) var e = window.event
e.target = ... ? ?
var r = confirm("Data will get lost!");
if (r == true) {
window.open("homepage.html", "_parent");
} else {
window.open(" ", "_parent"); // here I want to stay in the current pictures. I mean the current object map area. But how can I refer to it so it stays there ?
}
}
See the comments I added to your code ;)
var _images = { //Object-MapArea
start: {
path: 'start.jpg',
areas: [{
coords: '18,131,113,140',
text: 'Homepage',
clickHandler: doSomething // I changed the name to avoid confusion but you can keep onclick
}]
},
}
// ..... there is more code not shown here
//Creating DOM-Elements
var areaElem = document.createElement('AREA');
// Set attributes
areaElem.coords = area.coords;
areaElem.setAttribute('link', area.goto);
areaElem.setAttribute("title", area.text);
areaElem.setAttribute("shape", "rect");
// Add a listener on click event (using the function you defined in the area object above)
areaElem.addEventListener('click', area.clickHandler);
// Add your other click handler
areaElem.addEventListener('click', onArea_click);
_map.appendChild(areaElem);
function doSomething(e) {
// Get the area clicked
var areaClicked = e.target;
// I dont understand the following code...
var r = confirm("Data will get lost!");
if (r == true) {
window.open("homepage.html", "_parent");
} else {
window.open(" ", "_parent"); // here I want to stay in the current pictures. I mean the current object map area. But how can I refer to it so it stays there ?
}
}
Hope it helps ;)
I think I also Need to check the area if it is clicked or not
You are creating an element areaElem and attaching event to the same dom.
So there may not be need of any more check
You may not need to add both onclick & addEventListner on same element and for same event. Either onclick function or addEventListener will be sufficient to handle the event.
areaElem.onclick = function(event){
// Rest of the code
// put an alert to validate if this function is responding onclick
}
areaElem.addEventListener('click', onArea_click);
function onArea_click(){
// Rest of the code
}

Changing erik vold toolbarbutton image on the fly

I'm trying to make a firefox extension with the SDK. (if I can avoid XUL i'm happy)
I'm using erik vold toolbarbutton
But I need to change the toolbar image on the fly.
My lib/main.js (background page) is :
var tbb = require("toolbarbutton").ToolbarButton({
id: "My-button",
label: "My menu",
image: Data.url('off.png'),
onCommand: function(){
Tabs.open(Data.url("signin.html"));
}
});
tbb.setIcon({image:Data.url('on.png')});
console.log(tbb.image);
tbb.moveTo({
toolbarID: "nav-bar",
forceMove: false // only move once
});
tbb.image is correct, but the button isn't refreshed.
I tried to change packages/toolbarbutton-jplib/lib/toolbarbutton.js
function setIcon(aOptions) {
options.image = aOptions.image || aOptions.url;
getToolbarButtons(function(tbb) {
tbb.image = options.image;
tbb.setAttribute("image", options.image); // added line
}, options.id);
return options.image;
}
But it doesn't seem to refresh...
Is erik vold lib enough for this kind of need ?
also be sure to update with this fix https://github.com/voldsoftware/toolbarbutton-jplib/pull/13/files
there is a setIcon method and a image setter that you can use to update the toolbar button's image
I had the same problem so I just wrote the code my self using this tutorial:
http://kendsnyder.com/posts/firefox-extensions-add-button-to-nav-bar
Try this, I rewrote my code to fit your needs:
var btn = null;
var btnId = 'My-button';
var btnLabel = 'My menu';
var btnIconOn = 'on.png';
var btnIconOff = 'off.png';
var {Cc, Ci} = require('chrome');
var self = require("sdk/self");
var mediator = Cc['#mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
// exports.main is called when extension is installed or re-enabled
exports.main = function(options, callbacks) {
btn = addToolbarButton();
// do other stuff
};
// exports.onUnload is called when Firefox starts and when the extension is disabled or uninstalled
exports.onUnload = function(reason) {
removeToolbarButton();
// do other stuff
};
// add our button
function addToolbarButton() {
// this document is an XUL document
var document = mediator.getMostRecentWindow('navigator:browser').document;
var navBar = document.getElementById('nav-bar');
if (!navBar) {
return;
}
var btn = document.createElement('toolbarbutton');
btn.setAttribute('id', btnId);
btn.setAttribute('type', 'button');
// the toolbarbutton-1 class makes it look like a traditional button
btn.setAttribute('class', 'toolbarbutton-1');
// the data.url is relative to the data folder
btn.setAttribute('image', self.data.url(btnIconOff));
btn.setAttribute('orient', 'horizontal');
// this text will be shown when the toolbar is set to text or text and iconss
btn.setAttribute('label', btnLabel);
navBar.appendChild(btn);
return btn;
}
function removeToolbarButton() {
// this document is an XUL document
var document = mediator.getMostRecentWindow('navigator:browser').document;
var navBar = document.getElementById('nav-bar');
var btn = document.getElementById(btnId);
if (navBar && btn) {
navBar.removeChild(btn);
}
}
btn.addEventListener('click', function() {
Tabs.open(Data.url("signin.html"));
}, false);
tbb.setIcon({image:self.data.url(btnIconOn)});

Two divs click event works only on one div

I'm using jquery and ajax to create a drawer (#DrawerContainer) and load content into it if I click a thumbnail in a gallery. My function is almost finished but I want to be able to close that drawer if I click again the opening button (now #current).
Here is a jsfiddle of my code: http://jsfiddle.net/RF6df/54/
The drawer element appears if you click a square/thumbnail, it's the blueish rectangle.
The current thumbnail is turned green.
I added a button in my drawer (not visible in the jsfiddle) to close it. I use this part of code for this purpose and it's working like a charm.
// Close the drawer
$(".CloseDrawer").click(function() {
$('#DrawerContainer').slideUp()
setTimeout(function(){ // then remove it...
$('#DrawerContainer').remove();
}, 300); // after 500ms.
return false;
});
Now I need my #current div to be able to close #DrawerContainer the same way .CloseDrawer does in the code above. Unfortunately adding a second trigger like this $("#current,.CloseDrawer").click(function() to my function isn't working... When clicking my "current" thumbnail, it just reopen the drawer instead of closing it...
How can I modify my code to close my #DrawerContainer with the "current" thumbnail?
Please keep in mind that I'm learning jquery, so if you can comment it could be of a great help. And please do not modify my markup or css, since everything works beside the closing part.
As per my understanding, you can use "toggle()" function which does exactly the same (i.e, toggle visiblity).
$('#DrawerContainer').toggle();
EDIT:
Updated the script to work.
$(document).ready(function() {
$.ajaxSetup({cache: false});
$('#portfolio-list>div:not(#DrawerContainer)').click(function() {
if ($(this).attr("id") != "current")
{
// modify hash for sharing purpose (remove the first part of the href)
var pathname = $(this).find('a')[0].href.split('/'),
l = pathname.length;
pathname = pathname[l-1] || pathname[l-2];
window.location.hash = "#!" + pathname;
$('#current').removeAttr('id');
$(this).attr('id', 'current');
// find first item in next row
var LastInRow = -1;
var top = $(this).offset().top;
if ($(this).next().length == 0 || $(this).next().offset().top != top) {
LastInRow = $(this);
}
else {
$(this).nextAll().each(function() {
if ($(this).offset().top != top) {
return false; // == break from .each()
}
LastInRow = $(this);
});
}
if (LastInRow === -1) {
LastInRow = $(this).parent().children().last();
}
// Ajout du drawer
var post_link = $(this).find('.mosaic-backdrop').attr("href");
$('#DrawerContainer').remove(); // remove existing, if any
$('<div/>').attr('id', 'DrawerContainer').css({display: 'none'}).data('citem', this).html("loading...").load(post_link + " #container > * ").insertAfter(LastInRow).slideDown(300);
return false; // stops the browser when content is loaded
}
else {
$('#DrawerContainer').slideUp(300);
$(this).removeAttr("id");
}
});
$(document).ajaxSuccess(function() {
Cufon('h1'); //refresh cufon
// Toggle/close the drawer
$("#current,.CloseDrawer").click(function() {
$('#DrawerContainer').slideToggle()
setTimeout(function(){ // then remove it...
$('#DrawerContainer').remove();
}, 300); // after 500ms.
return false;
});
});
//updated Ene's version
var hash = window.location.hash;
if ( hash.length > 0 ) {
hash = hash.replace('#!' , '' , hash );
$('a[href$="'+hash+'/"]').trigger('click');
}
});
Also, updated it here: Updated JS Fiddle
EDIT -2: Updated Link
Hope this Helps!!

Can a JQuery plugin be called on a JQuery chain of methods or does it need to be called straight after a selector?

I'm having difficulty getting my textarea to expand vertically automatically.
I have some code to help make textarea auto expand vertically and for some reason it works when I clean out all my JS and provide a selector with reference to textarea e.g. $('textarea').autoGrow();
Calling the plugin on a chain of methods stops it from working. E.G.
micropostBox.hide().removeClass("micropost_content")
.addClass("micropost_content_expanded").show().autoGrow();
I established the plugin code works so copied all my working code to the same page and applied the autoGrow code to my textarea but it seems to be unresponsive. I noticed that the plugin I'm using the code from uses bind and unbind methods. In my code I use on and off methods from JQuery and wondering if this could be why the auto resizing of my textarea is not working?
Here is the code:
http://jsfiddle.net/erU5J/101/
autogrow plugin js code
$(function($) {
$.fn.autoGrow = function() {
return this.each(function() {
var txtArea = $(this);
var colsDefault = txtArea.attr('cols');
var rowsDefault = txtArea.attr('rows');
var updateSize = function() {
var linesCount = 0;
var lines = txtArea.attr('value').split('\n');
for (var i = lines.length - 1; i >= 0; --i) {
linesCount += Math.floor((lines[i].length / colsDefault) + 1);
}
if (linesCount >= rowsDefault) {
txtArea.attr('rows', linesCount + 1);
}
else {
txtArea.attr('rows', rowsDefault);
}
};
txtArea.unbind('.autoGrow').bind('keyup.autoGrow', updateSize).bind('keydown.autoGrow', updateSize).bind('change.autoGrow', updateSize);
});
};
});
my js code
$(function() {
$("div.microposts").on("focus", "textarea#micropostBox", function() {
var micropostForm = $(this).parent(),
micropostBox = micropostForm.find('textarea#micropostBox'),
micropostButton = micropostForm.find("input#micropostButton"),
xButton = micropostForm.find("div.xButton");
micropostBox.prop('rows', 7);
micropostForm.find('div#micropostOptions').removeClass('micropostExtraOptions');
micropostForm.find('div#postOptions').show();
$.trim(micropostBox.val()) == '' ? micropostButton.addClass("disabledMicropostButton").show()
:
micropostButton.prop('disabled', false);
micropostBox.hide().removeClass("micropost_content").addClass("micropost_content_expanded").show().autoGrow();
xButton.show();
micropostButton.prop('disabled', true);
micropostBox.off().on("keypress input change", function() {
micropostButton.prop({
disabled: !$.trim($(this).val()) != ''
});
$.trim($(this).val()) != '' ? micropostButton.removeClass("disabledMicropostButton").addClass("activeMicropostButton")
:
micropostButton.removeClass("activeMicropostButton").addClass("disabledMicropostButton");
});
xButton.on('click', function() {
micropostBox.removeClass("micropost_content_expanded").addClass("micropost_content");
micropostForm.find('div#micropostOptions').addClass('micropostExtraOptions');
micropostBox.val("");
micropostForm.find('div#postOptions').hide();
xButton.hide();
micropostButton.hide();
micropostBox.removeAttr('style');
micropostBox.prop('rows', 0);
micropostForm.find('.imagePreview > img').remove();
micropostForm.find('.imagePreview').hide();
});
});
});
$(function() {
$('div.microposts').on('click', 'li#addImage', function() {
var form = $(this).parents('form#new_micropost'),
fileField = form.find('input#micropost_image');
fileField.trigger('click');
});
});
$(function() {
$('input#micropost_image').change(function(evt) { //.off() make sautoresize work
var image = evt.target.files[0],
form = $(this).parents('form#new_micropost'),
imagePreviewBox = form.find('div.imagePreview'),
reader = new FileReader();
reader.onload = function(evt) {
var resultdata = evt.target.result,
img = new Image();
img.src = evt.target.result;
imagePreviewBox.show().prepend(img);
};
reader.readAsDataURL(image);
});
});​
textarea
<textarea class="micropost_content" cols="40" id="micropostBox" name="micropost[content]" placeholder="" rows="0"></textarea>
It would be best to view a working example on jsfiddle. My aim is to have the auto resizing of textarea working before and after an image is added to the page using the image upload button in the textarea.
Kind regards
It depends if the method preceding the plugin call returned the jQuery object containing the elements to where the plugins need to be attached.
Here are a few examples of methods that do and do not return the elements you started with:
$('element') //get an element
.contents() //get an elements contents
.wrapAll('<div>') //wrapAll contents with div and returns the contents, not wrapper
.parent() //the wrapper
.parent() //the element
.myPlugin() //we attach a plugin to element
$('<div>')
.appendTo('body') //appendTo returns the same element, the div
.myPlugin() //attaches to the div
$('element') //get an element
.text() //get its text
.myPlugin() //chaining isn't possible since text() returns a string
Better read the docs for every method in jQuery and what it returns. Some DOM methods usually return the same element, some don't, and some don't return elements but values.
In summary, can plugins be attached after chains? YES, and it depends.
Refer to the jQuery's documentation
http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability

Categories

Resources