Running a function onclick with a JSON file - json

So I'm trying to have a function run when i click on an image. It works with a normal image, but i'm getting the images from a reddit JSON file. I need the images to resize separately and I can't figure out how. It's probably something simple, but i'm still new to coding, so any help would be great.
$.getJSON("http://www.reddit.com/r/pcmasterrace/.json?jsonp=?", function (data) {
$.each(data.data.children, function (i, item) {
IsValidImageUrl(item.data.url, function (url, isvalid) {
if (isvalid) {
$('<img/>').attr('src', item.data.url)
.appendTo('#images')
.width(500)
.onclick = function() {Resize()};
}
});
});
});
Is the function right?
function Resize() {
if (document.getElementById('<img/>').style.width === "500px") {
document.getElementById('<img/>').style.width = "1000px";
} else {
document.getElementById('<img/>').style.width = "500px";
}
}
I think the ('<img/>') might be wrong. I tested it with ('test') and it worked, so do i need it to be something different? It worked with my test function so the .click worked so i think it's trying to change the wrong thing.

onclick is a property of DOM elements, not jQuery objects. You should use the click() function to add a click handler.
.getJSON("http://www.reddit.com/r/pcmasterrace/.json?jsonp=?", function (data) {
$.each(data.data.children, function (i, item) {
IsValidImageUrl(item.data.url, function (url, isvalid) {
if (isvalid) {
$('<img/>').attr('src', item.data.url)
.appendTo('#images')
.width(500)
.click(function() {Resize(this)});
}
});
});
});
Your Resize function should take an argument telling it which image to change:
function Resize(image) {
if (image.style.width == "500px") {
image.style.width = "1000px";
} else {
image.style.width = "500px";
}
}

Related

Puppeteer wait for specific console event

I am trying to implement a function that waits until a certain console event is sent.
E.g. there are several console.endTime calls being done (for performance debugging) and I want to wait until the last one (identified by a specific message text ) is done.
My code kind of works but the problem is that page.on adds new event listeners each time I call my waitForEvent function. I understand why that happens, but haven't found a solution that avoids this.
Code looks like this :
function waitForEndEvent() {
return new Promise((res, rej) => {
registerConsoleEvent(page, res, rej);
});
}
function filterMessage() {
return (msg) => {
try {
if (msg.type() == 'timeEnd') {
if (msg.text().includes("final time")) {
console.log('timeEnd:', msg.text());
res();
}
}
} catch (e) {
rej(e);
}
};
}
function registerConsoleEvent(page, res, rej) {
page.on('console', filterMessage(res,rej));
}
Any hint how I could solve this issue?
You can just remove the event listener after receiving the message. You can use the page.removeListener(...) method to remove the event listener. So the code would be like this
function waitForEndEvent() {
return new Promise((res, rej) => {
registerConsoleEvent(page, res, rej);
});
}
function registerConsoleEvent(page, res, rej) {
page.on('console', function consoleListener(msg) {
try {
if (msg.type() == 'timeEnd') {
if (msg.text().includes('final time')) {
console.log('timeEnd:', msg.text());
page.removeListener('console', consoleListener);
res();
}
}
} catch (e) {
rej(e);
}
});
}

DEBOUNCE JS NOT WORKING with event onclick was added at HTML Tag

I am learning about debounce js, and know its simple syntax as follows.
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
fn();
}, delay);
}
I create a button to test it as follow
<button id="test-debounce" onclick="testDebounce()">Click me</button>
function testDebounce().
function testDebounce() {
debounce(() => {
console.log('test debounce')
}, 500)
}
But it not work.
I try again with
document.getElementById("test-debounce").addEventListener('click', debounce(() => {
console.log('test debounce');
}, 500))
It's oke. I don't undetstand. Can anyone explain for me ?
Thanks.
debounce is designed to create a debounced function.
Every time you click you create a debounced function which you never call.
Create the function once:
const testDebounce = debounce(() => {
console.log('test debounce')
}, 500);
… and then use that as the event listener.

How to Debounce with Observer Polymer

I am trying to run getResponse once when a web components finishes loading. However, when I try to run this, the debounce function just acts as an async delay and runs 4 times after 5000 ms.
static get properties() {
return {
procedure: {
type: String,
observer: 'debounce'
}
}
}
debounce() {
this._debouncer = Polymer.Debouncer.debounce(this._debouncer, Polymer.Async.timeOut.after(5000), () => {
this.getResponse();
});
}
getResponse() {
console.log('get resp');
}
What is necessary to get getResponse to run once upon the loading of the element?
Are you sure you want to use a debouncer for that? you could just use the connectedCallBack to get a one Time Event
class DemoElement extends HTMLElement {
constructor() {
super();
this.callStack = 'constructor->';
}
connectedCallback() {
this.callStack += 'connectedCallback';
console.log('rendered');
fetch(this.fakeAjax()).then((response) => {
// can't do real ajax request here so we fake it... normally you would do
// something like this.innerHTML = response.text();
// not that "rendered" get console logged before "fetch done"
this.innerHTML = `
<p>${this.callStack}</p>
<p>${response.statusText}</p>
`;
console.log('fetch done');
}).catch(function(err) {
console.log(err); // Error :(
});
}
fakeAjax() {
return window.URL.createObjectURL(new Blob(['empty']));
};
}
customElements.define('demo-element', DemoElement);
<demo-element></demo-element>
If you really need to use an observer you could also set a flag this.isLoaded in your connectedCallback() and check for that in your observer code.

How to create function to get data from WCF Rest then display to table

I have declare function to get WCF Rest the name is service.js, the url get Json data. Then I create another function to get data entryCtrl.js then show to html
service.js
(function (app) {
app.service("CRUD_AngularJs_RESTService", function ($http) {
this.getAllEntry = function () {
return $http.get("http://localhost:51458/ServiceRequest.svc/GetAllRequest/");
};
});
})(angular.module('model'));
entryCtrl.js
(function (app) {
'use strict';
app.controller('entryCtrl', entryCtrl);
entryCtrl.$inject = ['$scope'];
function entryCtrl($scope) {
$scope.pageClass = 'page-entry';
$scope.GetAllRecords = function() {
var promiseGet = CRUD_AngularJs_RESTService.getAllEntry();
promiseGet.then(function (pl) { $scope.EntryData = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
}
})(angular.module('model'));
view entry.html
<table data-ng-controller="entryCtrl">
<tbody data-ng-repeat="entry in EntryData">
<tr>
<td>{{entry.name}}</td>
<td>{{entry.telpon}}</td>
<td>{{entry.foobar}}</td>
</tr>
</tbody>
</table>
I don't have any error, my data in table not show anything. What must I try to know the function it's work or not?
jush have warning XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. I don't know what it is mean.
The function GetAllRecords() is not set to the $scope. You need to set $scope.GetAllRecords = GetAllRecords before the call to $scope.GetAllRecords():
function entryCtrl($scope) {
$scope.pageClass = 'page-entry';
$scope.GetAllRecords = function() {
var promiseGet = CRUD_AngularJs_RESTService.getAllEntry();
promiseGet.then(function (pl) { $scope.EntryData = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
$scope.GetAllRecords();
}
Alternatively, you can simply call GetAllRecords() directly, since you don't seem to need it in the $scope:
function entryCtrl($scope) {
$scope.pageClass = 'page-entry';
(function() {
var promiseGet = CRUD_AngularJs_RESTService.getAllEntry();
promiseGet.then(function (pl) { $scope.EntryData = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
})();
}

submit form using mootools

I have made a class that handles load and submit of a html form. See code below
ND.Form = new Class({
//--- Implements options og events.
Implements: [Options, Events],
//--- Options.
options: {
url: '',
injectTo: ''
},
//--- Initialize the class.
initialize: function (panel, options) {
//--- Set options
this.setOptions(options);
this.panel = panel;
this.loadForm();
},
loadForm: function () {
var req = new Request.HTML({
url: this.options.url,
method: 'get',
onSuccess: function (html) {
$(this.options.injectTo).empty();
$(this.options.injectTo).adopt(html);
var formId = $(this.options.injectTo).getFirst('form').get('id');
$(formId).addEvent('submit', function (e) {
e.stop();
this.submitForm(formId);
} .bind(this));
} .bind(this)
}).send();
},
submitForm: function (formId) {
$(formId).set('send', {
onSuccess: function (resp) {
this.panel.loadContent();
if (resp != null) {
$('lbl_error').empty();
$('lbl_error').setStyles({ 'display': 'block', 'color': 'red' }).set('html', resp);
}
}.bind(this),
onFailure: function (resp) {
if (resp != null) {
$('lbl_error').empty();
$('lbl_error').setStyles({ 'display': 'block', 'color': 'red' }).set('html', resp);
}
}
});
$(formId).send();
}
});
And it all works just fine, exept that when i push the save button more than ones the "this.panel.loadContent();" in the "submitForm: function (formId)" fires the same x amount of times I have pushed the button, how can i prevent this ?
/Martin
Starting from mootools 1.3 "set('send')" adds another one event.
So You need to write:
$('myForm').set('send', {
onSuccess: function (html) {},
onFailure: function(xhr){}
}).addEvent('submit', function(e){
e.stop();
this.send();
});
instead of:
$('myForm').addEvent('submit', function(e){
e.stop();
this.set('send', {
onSuccess: function (html) {},
onFailure: function(xhr){}
});
}).send();
Then Request will be sent only once each time when You handle form.
Basically we need to do three things:
Listen for the ‘click’ event on the submit button.
Stop the event from submitting the form.
Send the form using $(formElement).send()
A solution could look something like this:
$('submit').addEvent( 'click', function(evt){
// Stops the submission of the form.
new Event(evt).stop();
// Sends the form to the action path,
// which is 'script.php'
$('myForm').send();
} );
I have used the request.send() method but googled trying to find a way to just replicate the action of a user hitting a form submit button, but with also allowing some javascript logic being performed beforehand. I did not find anything in discussions specifically addressing this. The answer I found is to use the form.submit() method.