I'm trying to build my first plugin using jquery.
So far successful, but I'm stuck in deleting the notifications.
I was able to delete the notification on a click event.
Notification.prototype.destroy = function(element) {
var self = this;
element.closest('.notification-container').remove();
};
And I call that function inside init method.
Notification.prototype.init = function() {
var self = this;
self.$el.on('click', function() {
self.build();
});
self.$body.on('click', '.close', function() {
self.destroy(this);
})
};
Now I wanted to give a auto close option to the user, and I thought of using the setTimeout function, but as I've created the function passing the parameter as current element, I'm unable to get it.
Here's the pen.
Any help will be much appreciated.
Thanks!
You had several problems there:
The setTimeout function must be called upon display (and not upon build), otherwise it can be called even before you display the notification (hence your notification will not be automatically removed).
When you call the setTimeout in order to destroy the notification - you need to pass the container of the notification you just created, so the destroy function will be able to find the relevant element to remove (when you use the click option - you pass the X element, so it's easy to find the closest container, but when you use the setTimeout you must pass the container element himself).
I think all of the changes I made are in the build function, here it is:
Notification.prototype.build = function() {
var self = this;
var closeHTML = self.options.autoClose ? '' : '';
if (self.options.type == 'thumb') {
var $notificationHTML = $('<div class="notification-container">' +
'<i class="close">x</i>' +
'<div class="notification">' +
'<div class="thumb-container">' +
'<img src="' + self.options.src + '">' +
'</div>' +
'<p>' + self.options.text + '</p>' +
'</div>' +
'</div>');
} else {
var $notificationHTML = $('<div class="notification-container">' +
'<i class="close">x</i>' +
'<div class="notification ' + self.options.style + '">' +
'<p>' + self.options.text + '</p>' +
'</div>' +
'</div>');
}
self.$body.prepend($notificationHTML);
if(self.options.autoClose) {
setTimeout(function() {
self.destroy($notificationHTML);
}, 5000)
} else {
self.$body.on('click', '.close', function() {
self.destroy(this);
})
}
};
And a working codepen:
http://codepen.io/anon/pen/JKgPgB?editors=0010
Related
When the button is clicked, 2 sets data is added. I use material design.
Button needs 2 clicks to run function for first time. Due to this, the data is added to table 2 times.
Code
HTML
<button onclick="purchaseList(orderid)" id="dialog">Button</button>
JS
function popup(listid) {
var starCountRef = firebase.database().ref('Orders/' +
listid).child('foodItems');
starCountRef.on('child_added', snapshot => {
var snaps = snapshot.val();
var itemPrice = snaps.price;
var itemName = snaps.productName;
var itemQuantity = snaps.quantity;
console.log(itemName);
$("#producttable").append(
'<tr><td class="mdl-data-table__cell--non-numeric">' + itemName +
'</td><td>' + itemQuantity + '</td><td>' + itemPrice + '</td></tr>'
);
});
var dialog = document.querySelector('dialog');
var showDialogButton = document.querySelector('#dialog');
if (!dialog.showModal) {
dialogPolyfill.registerDialog(dialog);
}
showDialogButton.addEventListener('click', function() {
dialog.showModal();
});
dialog.querySelector('.close').addEventListener('click', function() {
var element = document.getElementById("producttable")
while (element.lastChild) {
element.removeChild(element.lastChild);
}
dialog.close();
});
}
This should work:
var element = document.getElementById("producttable")
while (element.lastChild) {
element.removeChild(element.lastChild);
}
Add this as necessary.
I suggest you change your firebase function from using .on to .once to avoid multiple additions of data to your table and as your data isn't expected to change frequently or require active listening you better use .once for performance benefits.
firebase.database().ref('Orders/' +
listid + '/foodItems').once('value').then(function(snapshot) {
// the rest of your code goes here
});
this remocve element with class name ".mdl-data-table__cell--non-numeric"
when user click .close
dialog.querySelector('.close').addEventListener('click', function () {
dialog.close();
$(".mdl-data-table__cell--non-numeric").remove();
});
UPDATE:
to open dialog on 2nd click use pseudo element to activate like this
<div class=pseudo><button onclick="purchaseList(orderid)"id="dialog" disabled>Button</button></div>
var i=0;
$('.pseudo').click(function(){
i++;
if(i==2){
$("#dialog").prop('disabled',false);
}
});
I'm trying to use an array and for-loop to index and name some Howls and Howl trigger buttons.
I've referenced this question for what I'm trying to achieve: Howler - Random sound
The difference with mine is that it's without the random aspect plus I've added some method calls.
I'm adding the buttons used to trigger the Howls into the loop and that's where it seems to be failing - namely when the buttons are clicked.
Console reports the following when either button is clicked:
Uncaught TypeError: Cannot read property 'play' of undefined
Specifically referring to this: sounds[i].play(); or sounds[i].pause();
Here's the JS:
var sounds = ['sound1', 'sound2'];
var howls = {};
for (var i=0; i<sounds.length; i++) {
howls[sounds[i]] = new Howl({
urls: ['http://powellian.com/assets/audio/' + sounds[i] + '.mp3', 'http://powellian.com/assets/audio/' + sounds[i] + '.ogg'],
volume: 1,
onplay: function() {
console.log('Playing: ' + sounds[i]);
$(sounds[i]).removeClass('static').addClass('playing');
$(sounds[i] + ' span.ascii-play').addClass('hide');
$(sounds[i] + ' span.ascii-pause').removeClass('hide');
},
onpause: function() {
console.log('Paused: ' + sounds[i]);
$(sounds[i]).removeClass('playing').addClass('paused');
$(sounds[i] + ' span.ascii-play').removeClass('hide');
$(sounds[i] + ' span.ascii-pause').addClass('hide');
},
onend: function() {
console.log('Finished: ' + sounds[i]);
$(sounds[i]).removeClass().addClass('static');
$(sounds[i] + ' span.ascii-play').removeClass('hide');
$(sounds[i] + ' span.ascii-pause').addClass('hide');
}
});
// PLAY btn
$('#' + sounds[i] + ' span.ascii-play').on('click', function (e) {
sounds[i].play();
});
// PAUSE btn
$('#' + sounds[i] + ' span.ascii-pause').on('click', function (e) {
sounds[i].pause();
});
}
I had a non-array/for-loop version working fine with 2 Howls, and the add/remove class stuff works fine so please ignore that.
I will eventually be generating 16 Howls from the array.
Here's a fiddle which includes the markup structure: Howler Fiddle
Any help would be appreciated, thanks in advance.
There are two issues that I see here:
You are referencing the variable i inside the click handler without maintaining scope. Because of this, it will always see i as the last value. You could use bind as one way of fixing this:
$('#' + sounds[i] + ' span.ascii-play').on('click', function (i2, e) {
sounds[i2].play();
}.bind(null, i));
You are trying to call play on sounds, which isn't holding the reference to the Howl object. You should be calling play on howls[sounds[i2]] instead.
EDIT: In this case it is just easier to use a forEach, so I've updated your fiddle to do that and fix the scoping issues here: http://jsfiddle.net/zmjz7sf3/1/.
Im new to using Electron and also kinda new to using the webview tag, so I pre-apologize for maybe not knowing something really obvious.
Im trying to dynamiclly create web views and add the following events to them.
did-start-loading
did-stop-loading
did-finish-load
page-title-updated
dom-ready
Im using a mix of Jquery and pure javascript to do this but currently im not having much luck. I have attached my code below so you can try find anything obvious there. Im not getting any javascript errors in the debug menu but at the same time none of it seems to be working.
function AddTab(URL){
tabcount++;
var NewTab = '<li href="#content-' + tabcount + '" id="tab' + tabcount + '" class="current"><img src="System_Assets/icons/Logo.png" /><span>Tab Home</span><a class="TabClose" href="#"></a></li>';
var NewContent = '<div id="content-' + tabcount + '" class="ContentHolder" style="display:block;"><webview id="webview-content-' + tabcount + '" src="http://www.ohhaibrowser.com"></webview></div>';
ChangeCurrent("");
//Hide current tabs
$(".ContentHolder").css("display", "none");
//Show new tab
$("#tabs-menu").append(NewTab);
$("#BrowserWin").append(NewContent);
$("#CurWebWin").val("webview-content-" + tabcount);
AddListeners("webview-content-" + tabcount,"tab" + tabcount);
UpdateTabCount();
}
function UpdateTabCount(){
$("#HideShow").text(tabcount);
}
function AddListeners(webview,tabid)
{
element = document.getElementById(webview);
element.addEventListener("did-start-loading", function() {
loadstart(tabid);
});
element.addEventListener("did-stop-loading", function() {
loadstop(tabid,webview);
});
element.addEventListener("did-finish-load", function() {
loadstop(tabid,webview);
});
element.addEventListener("page-title-updated", function() {
loadstop(tabid,webview);
});
element.addEventListener("dom-ready", function() {
domloaded(tabid,webview);
});
}
function loadstart(tabid)
{
$("#" + tabid + " span").val('Loading...');
//$("#" + tabid + " img")
}
function loadstop(tabid, webview)
{
$("#" + tabid + " span").val('');
}
function domloaded(tabid, webview)
{
element = document.getElementById(webview);
$("#" + tabid + " span").val(element.getURL());
}
You have to set Preload call to make change in Webview
browser.html
<script src="browser.js"></script>
<webview src="https://www.google.com/watch?v=1osdnKzj-1k" preload="./inject.js" style="width:640px; height:480px"></webview>
create sample js file name called inject.js
inject.js
__myInjection={
onloada : function() {
var script = document.createElement("script");
script.src = "https://code.jquery.com/jquery-2.1.4.min.js";
$("#header").html('<h1>Sample work</h1>\
<p>Hello, Google</p>\
Click me');
document.body.appendChild(script);
}
}
now in browser.js
onload = function() {
var webview = document.querySelector('webview');
webview.addEventListener("dom-ready", function(){
webview.executeJavaScript('__myInjection.onloada ()')
// webview.openDevTools();
});
doLayout();
I have the following which works fine:
$('<li><a id=' + loc.locId + ' href="/DataEntry" rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
$("#btnList a").click(function () {
alert(siteName);
localStorage["dataEId"] = $(this).attr("id");
localStorage["dataESiteName"] = siteName;
localStorage["dataESysName"] = sysName;
localStorage["dataELocName"] = $(this).text();
}
When I have the following, I can't even get to the click to display an alert message:
$.getJSON('/Home/GetLocType', { "locId": loc.locId }, function (result) {
var str = JSON.stringify(result);
if (str == '1') {
$('<li><a id=' + loc.locId + ' href="/DataEntry" rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
} else {
$('<li><a id=' + loc.locId + ' href="/DataEntry/PotableForm" rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
}
$("#btnList").listview('refresh');
});
$("#btnList a").click(function () {
alert(siteName);
localStorage["dataEId"] = $(this).attr("id");
localStorage["dataESiteName"] = siteName;
localStorage["dataESysName"] = sysName;
localStorage["dataELocName"] = $(this).text();
}
Note sure what the difference is. I need to use Json as based on value, I need to go to a either of the 2 hyperlinks.
Use event delegation since anchor is created dynamically in your ajax call or bind the event (only for the added element) inside the ajax success callback. on syntax will work if your jquery version >= 1.7 for earlier versions take a look at live
$("#btnList").on('click', 'a', function () {
alert(siteName);
localStorage["dataEId"] = $(this).attr("id");
localStorage["dataESiteName"] = siteName;
localStorage["dataESysName"] = sysName;
localStorage["dataELocName"] = $(this).text();
}
Your first syntax works because it binds the click event to the anchor that exists underneath btnList, but it doesn't bind event to the ones added during the ajax calls in a later point in time.
I have some json that's loaded into li.ui-state-default pending user entry.
The user can then enter a new entry. I want it to empty li.ui-state-default every time a new entry is loaded but it seems to just stay empty.
//data for DOM
var timeout = '';
$('.call-json').keyup(function () {
clearTimeout(timeout);
var val = this.value;
timeout = setTimeout(function () {
$('.ui-state-default').empty();
$.getJSON('json/' + val + '.json', function (data) {
// load data
var items = [];
for (key in data[0].attributes) {
if (key.match('.stat.prop.type')) {
items.push(data[0].attributes[key])
}
};
displaySortLabel(items, "type-details");
function displaySortLabel(items, parentClass) {
$('<span/>', {
'class': 'el-data',
html: items.join('')
}).hide().fadeIn().appendTo('.' + parentClass + ' .sort-label');
}
Appending to li.ui-state-default by using .appendTo('.' + parentClass + ' .sort-label') will not work as it searches for a .sort-label to be present inside that parentClass variable.
Make sure you have the correct selector while trying to append.
Furthermore, you don't need to hide() and fadeIn():
$('<span/>', {
'class': 'el-data',
html: items.join(''),
'css': {
'display': none
}
}).fadeIn().appendTo('.' + parentClass + ' .sort-label');