Binded click event firing on page load - javascript

I have a function called getMedia() which fires an ajax call to get some content. I also have some filters at the top and onclick I've binded an even to destory the content grid and fetch new content but it is firing off when the document loads.
$(document).ready(function() {
var numposts = $(".social__board").data('numposts');
$.each(accounts, function(key, value) {
getMedia(".board", key, value, numposts);
});
setGridFilter(".filters", ".board", ".grid-item");
});
and then in the same file I have the setGridFilter function.
function setGridFilter(filters, board, griditem) {
$(filters + " li").first().addClass("active");
$(document).on("click", $(filters + " li"), function(){
$(griditem).remove();
$(this).addClass('active');
$(this).siblings().removeClass("active");
var source = $(this).data("source");
var numposts = $(board).data('numposts') * 3; // MORE POSTS FOR SINGLE CHANNEL
var username = $(board).attr("data-" + source);
console.log("Source: " + source + "Numposts: " + numposts + "Username" + username);
getMedia(board, source, username, numposts);
});
}

Related

access to DOM add dynamiclly, getScript, ajax

I use jQuery ajax to read context on my page dynamicly. But part of DOM is load in javaScript function call by getScript in ajax .done. But just after I load new content I need to get elements by class and use it in next function. Unfortunatly I can't find elements, that I create in javaScript function, and script with that function I call using jQuery getScript.
ok, my code:
$(document).ready(function() {
$('.link').click(function(){
var subpage = $(this).attr('data-subpage');
var src = 'subpages/'+ subpage + '/' + subpage +'.php';
var script = 'subpages/'+ subpage + '/js/' + subpage +'.js';
$.ajax({
url: src,
context: document.body,
dataType: 'html',
success: function(responseText){
$('#text').html(responseText); // responseText has only container <div id="insideText"></div> that I use in one function and load there by html() several divs. One of this div has class 'translate'. I need it in function Translator
}
})
.done(function(){
$.getScript(script); // here I call script where I load several divs to #insideText
Translator($('.active').attr('data-lang')).getTranslation() // part of function have to find all div.translate, but can't find it if they're load in script call in getScript. And this is a problem.
})
})
})
I hope, I explaine my problem quite clear. If not, plaese ask, I'll try again.
There's some way to do that?
//update//
After this script, call by getScript I still have problem with second 'done':
const Presenter = function(){
var presented, show, fullDesc, cont;
presented = [
{
url: 'demo/colorsGame/',
name: 'Graj w kolorki!',
desc: 'Graj w kolorki! Wybierz taki sam kolor, w jakim napisana jest nazwa wylosowanego koloru. Spiesz się, czas ucieka coraz szybciej i szybciej. Uważaj, bo mózg może cię oszukać i uznać za ważniejsze to, co jest napisane, a nie to co widzisz. Zobacz ile punktów jesteś w stanie zdobyć zanim popełnisz trzy błędy. Ćwicz swoją koncentrację.'
},
{
url: 'demo/sampleUserProfile/',
name: 'Sample User Profil',
desc: 'Mała próbka możliwości reactJS. Wkonany z użyciem biblioteki reactJS, menadzera pakietów webpack oraz na środowisku nodeJS przykładowy profil użytkownika. Like-uj i obserwuj do woli, a jeśli chcesz, wypowiedz się pod profilem.'
}
];
show = function(url, desc, name) {
fullDesc =
"<a href ='" + url + "'>" +
"<h1 class='translate'>" + name + "</h1>" +
"</a>" +
"<div>" +
"<p class='translate'>" + desc + "</p>" +
"</div>";
cont =
"<div id='webmin' class='clearfix'>" +
"<div>" +
fullDesc +
"</div>" +
"<div>" +
"<iframe src='" + url + "' scrolling='no'>" +
"ups, twoja przeglądarka nie obsługuje ramek" +
"</iframe>" +
"</div>"+
"</div>";
return cont;
};
return {
show: show,
presented: presented
}
};
display = function(){
var len, url, name, desc;
len = Presenter().presented.length;
for(let i = 0; i <= len; i++){
url = Presenter().presented[i].url;
name = Presenter().presented[i].name;
desc = Presenter().presented[i].desc;
$('#insidetext.apps').append(Presenter().show(url, desc, name));
}
};
display();
Hmm, I'm wondering, if iframe is not a problem here? And don't let script to be done to end?
getScript is just another ajax call and returns an xhr object which exposes done and fail methods. Use those methods to ensure your dom is properly loaded before trying to access it.
$(document).ready(function() {
$('.link').click(function(){
var subpage = $(this).attr('data-subpage');
var src = 'subpages/'+ subpage + '/' + subpage +'.php';
var script = 'subpages/'+ subpage + '/js/' + subpage +'.js';
$.ajax({
url: src,
context: document.body,
dataType: 'html'
})
.done(function(responseText){
$('#text').html(responseText);
$.getScript(script).done(function() {
Translator($('.active').attr('data-lang')).getTranslation() ;
}
})
})
})
Also, you should implement the .fail methods, in case your ajax requests fail.

Saving data to parse using javaScript SDK

Using parse.com and JavaScript SDK.
- Section one shows a list of objects
- Section two lets the user select one of those objects and add to a modal box
- Section three saves the data to parse
What I'm unable to work out is how I can save the section 1 item.badgename and item.category to parse.
I've tried adding myBadge.set("category", badgename.toString()); to section 3, but I get a undefined error. i'm not sure how to define this before trying to save.
Really need some help and an example to follow.
3 -Saves the badge details to parse
var MyBadge = Parse.Object.extend("myBadges");
var FriendRequest = Parse.Object.extend("FriendRequest");
var friendRequest = new FriendRequest();
friendRequest.id = window.selectedFriendRequestId;
var badgeselected = $('#badgeselect .go').attr("src");
$(document).ready(function() {
$("#send").click(function() {
var myBadge = new MyBadge();
var badgeselected = $('#badgeselect img').attr("src");
var BadgeSentTo = $('#selectFriend').val();
var categorySelected = $('#category').val();
var uploadercomment = $('#UploaderComment').val();
myBadge.set("BadgeName", badgeselected); //got this working using .set
myBadge.set("Comment", uploadercomment); //got this working using .set
myBadge.set("category", categorySelected);
myBadge.set("SentTo", new Parse.User({
id: BadgeSentTo
}));
myBadge.set("uploadedBy", Parse.User.current());
myBadge.save(null, {
success: function(results) {
console.log("Done");
//location.reload();
},
error: function(contact, error) {
// The save failed.
alert("Error: " + error.code + " " + error.message);
}
});
return false;
});
});
** 1- Returns results to the page for user to select**
var GlobalBadges = Parse.Object.extend("Global_Badges");
var query = new Parse.Query(GlobalBadges);
query.exists("Global_Badges_img");
query.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('Global_Badges_img'),
//friendRequestId: results[i].id,
badgename: results[i].get('BadgeName'),
category: results[i].get('category')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function(item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div></div>');
wrapper.append('<img class="images BadgeImgOutline responsive-image" src="' + item.imageURL + '" />'+ '<br>');
wrapper.append('<div id="name"class="tag badgelabel" >'+ item.badgename + '</div>'+ '<br>');
wrapper.append('<div id="category" class="tag categorylabel" >'+ item.category + '</div>'+ '<br>'+ '<br>' );
$('#container').append(wrapper);
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
2 -Upon the user selecting an object from above, this adds the data to a modalbox
$(document).ready(function() {
$('.go img').css('cursor', 'pointer');
$('.go').on('click', 'img', function(e) {
$('.go img').removeClass('BadgeImgOutline');
$(this).parent().appendTo('#badgeselect');
$(this).addClass('BadgeImgOutlineSmall');
$('.go img').addClass('BadgeImgOutline');
$('#modal').reveal({
closeonbackgroundclick: true,
dismissmodalclass: 'close'
});
return false;
});
});
This was addressed by making the following changes.
- Taking the data from #badgeSelect not #category
- From section 3, the line var categorySelected = $('#category').val(); was changed to categorySelected = $('#badgeselect .categorylabel').text();
By taking the data from #badgeSelect it meant that the only data being available was that shown shown in the text box, instead of '#category'that returned all results.
The it was simply targeting the text correctly with the change to the var categorySelected

How to get more JSON data on scroll or while scrolling?

I have the following code below which returns some results when the user searches a term.
Once i get some results,I want to add feature which will allow me to get more data when scrolling down ward?
NOTE: I dont want to use any plugin(s).
$(document).ready(function() {
$("#submit").click(function (event) { // wire up this as an onclick event to the submit button.
var searchTerm = $("#search").val(); // get the user-entered search term
var URL = "http://api.flickr.com/services/feeds/photos_public.gne";
//var URL = "http://api.flickr.com/services/feeds/photos_public.gne";
var ID = "25053835#N03";
//var MYID-"84215563#N08";
//var tagmode="&tagmode=any";
//var format ="&format=json";
var tags="&tags="+ searchTerm;
var tagmode="&tagmode=any";
var jsonFormat = "&format=json&jsoncallback=?";
var ajaxURL= URL+"?jsoncallback=?id="+ID+tags+tagmode+jsonFormat;
//var ajaxURL= URL+"?"+tags+tagmode+jsonFormat;
$.getJSON(ajaxURL,function(data){
//$("h1").text(data.title);
//alert(data.length);
var photoHTML;
$("#photos").empty();
if (data.items.length) {
alert(data.items.length);
$.each(data.items, function(i,photo) {
//var photoHTML = "<h4>" +photo.tags + "</h4>";
photoHTML = "<p>";
photoHTML += '<a href="' + photo.link + '">';
photoHTML += '<img src="' + photo.media.m + '" alt="' + photo.media.m + '" title="' + photo.media.m + '"></a>';
photoHTML = "</p>";
$('#photos').append(photoHTML).fadeIn(200);
});
} else {
alert(data.items.length);
photoHTML = "<h2> No Results</h2>";
$('#photos').append(photoHTML).fadeIn(200);
}
//$('#photos').append(photoHTML).fadeIn(200);
});
});
});
You could use the jquery .scroll() method. You have two options, save all data when page loads then display as user scrolls OR make ajax request every time there is a scroll down request.
$("#yourSelector").on('scroll', function(){
// do stuff
});
or simply using the shortcut:
$("#yourSelector").scroll(function(){
// do stuff
});
I hope this helps!
Here is a link to jquery scroll api to know about the options (such as specifying scroll DOWN): http://api.jquery.com/scroll/
You can also bind scroll event using jquery:
Put your whole code into a function:
function myfun(){
//-- you code
}
and call myfun() from both event:
on click event-
$("#submit").click(function (event) {
myfun();
});
on scroll event -
$("#yourSelector").scroll(function(){
myfun();
});

calling JQuery HTTP GET request inside javascript function

I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}
//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}
jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});
Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}

Injecting code into the web page does not work

This is a follow-up to a question I asked yesterday.
I have a userscript (kind of like GreaseMonkey script, but for Chrome).
The idea is to add a textbox and a button to the page. Then when the user clicks the button, it kicks off a function that does stuff. So I inject the textbox, button and the function into the page, but when the user clicks the button, the Chrome console tells me "Uncaught TypeError: object is not a function". So obviously it does not see the function I just injected and that is specified in the onclick event for the button.
So I have code like this:
initialize();
function initialize() {
var dropDown = document.getElementById("tstGlobalNavigation_ddlChooseProject");
// add a textbox
dropDown.innerHTML = dropDown.innerHTML + " <input type='text' name='txtSearch' style='position:absolute;top:8px;left:800px;width:50px' >";
// add a button
dropDown.innerHTML = dropDown.innerHTML + " <input type='button' name='btnSearch' value='Go' onclick='fn()' style='position:absolute;top:8px;left:860px;width:35px'>";
addScript("var obj = document.getElementById('txtSearch'); "
+ "if (obj != null) { "
+ " var incidentId = document.getElementById('txtSearch').value; "
+ " var currentURL = location.href; "
+ " var splitResult = currentURL.split('/'); "
+ " var projectId = splitResult[4]; "
+ " location.href = 'http://dev.myApp.com/ProductTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; "
+ " }"
, "fn");
}
function addScript(contents, id) {
var head, script;
head = document.getElementsByTagName('head')[0];
script = document.getElementById(id);
if(script != undefined) {
head.removeChild(script);
}
script = document.createElement('script');
script.type = 'text/javascript';
script.id = id;
script.innerHTML = contents;
head.appendChild(script);
}
What am I missing here?
You're not calling the function you created, you're using the id that you give to the script tag... Try changing the code to
addScript("function fn() { var obj = document.getElementById('txtSearch'); "
+ "if (obj != null) { "
+ " var incidentId = document.getElementById('txtSearch').value; "
+ " var currentURL = location.href; "
+ " var splitResult = currentURL.split('/'); "
+ " var projectId = splitResult[4]; "
+ " location.href = 'http://dev.myApp.com/ProductTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; "
+ " } }"
, "fn");
and you will have a fn() function that can be called
The problem is that you're trying to use the onclick element attribute to bind an event handler. These attributes are only parsed when the page is first loaded, at which time the function you're trying to bind as the callback doesn't exist.
Avoid binding event handlers in element on* attributes whenever possible. This is called writing unobtrusive JavaScript.
That said, if you absolutely must stick with using onclick, you can bind to a dummy function which does nothing but turn around and call the function that you inject:
<button onclick="wrapper()"
Where wrapper looks something like this:
function wrapper() {
return functionThatWillEventuallyBeInjected();
}
I'm not sure you can actually create script tags on the fly and push content in it.
You could instead create the script tag and modify the src attribute to some JS file:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "path/to/your/javascript.js";
document.body.appendChild(script);
If you really need to execute a code stored in a string, maybe you could simply eval() it when required!

Categories