Javascript menu dropdown not triggering function on click - javascript

So i've been messing around and searching and it triggers when i don't generated the code via my JS and put the output as html on the file.
The menu is supposed to be dynamic and generate subs on it and subs have products and so on i was doing it and logically is correct but can't know if JS is confliting some part of this code.
JS Generate Menus:
$(function(){
var ul = $('#category-content');
var subcategoryLi = $('#sublist');
var productsLi = $('#productList');
init();
function init(){
GetCategorys();
}
function BuildSubCategorys(id,sub){
var content = '';
if (typeof(sub) != 'undefined' && sub.length > 0){
for(var i = 0; i < sub.length; i++){
if (sub[i].c_parentcat == id){
content += AddSubItem(sub[i].c_name,sub[i].c_id);
}
}
return content;
}
else{
return '';
}
}
function hasSubs(j,d){
for(var i=0;i<d.length;i++){
if(d[i].c_parentcat == j ){
return true;
}
}
}
function BuildCategorys(root){
var content = AddCategoryHeader('Categorias');
var subs = [];
if (typeof(root) != 'undefined' && root.length > 0){
for(var i = 0; i < root.length; i++){
if (root[i].c_parentcat == -1){
content += AddCategory(root[i].c_name,root[i].c_id);
if (hasSubs(root[i].c_id, root) == true){
var subContent = BuildSubCategorys(root[i].c_id, root);
subs[root[i].c_id] = CreateSubList(subContent);
}
}
}
ul.append(content);
ul.append(AddSeparator());
for(var j = 0; j < root.length; j++){
curr_id = root[j].c_id;
ul.find('#category'+curr_id).append(subs[curr_id]);
}
}
else {
ul.append(AddCategoryHeader('Categorias'));
ul.append(HandleNoSubData());
ul.append(AddSeparator());
}
//Build the products
GetCategoryProducts();
}
function BuildProducts(p){
var content = AddCategoryHeader('Produtos sem categoria');
var category_items = [];
if (typeof(p) != 'undefined' && p.length > 0){
for(var i=0; i < p.length; i++){
if (p[i].p_categoryid == -1){
//he has no category so lets add it to the non category section
content += AddProduct(p[i].p_name,p[i].p_id);
}
else {
subcategoryLi.find('#subcategory'+ p[i].p_categoryid).append(AddProduct(p[i].p_name,p[i].p_id));
}
}
ul.append(content);
//LEFT: LINK ON THE PRODUCT WITH THEIR ID ON CREATE FUNCTION
}else{
ul.append(AddCategoryHeader('Produtos sem categoria'))
ul.append(HandleNoProdData());
}
}
function AddSeparator(){
return '<li role="separator" class="divider"></li>';
}
function AddCategoryHeader(name){
return '<li class="dropdown-header">' + name +'</li>';
}
function AddCategory(name,id){
return '<li class="dropdown-submenu" id="category'+id+'"><a id="menu-itex" tabindex="-1" href="javascript:;">' + name + ' <span class="caret"></span></a></li>';
}
function AddProduct(name,id){
return '<li>' + name + '</li>';
}
function AddSubItem(name,id){
return '<li> '+ name + ' </li>';
}
function CreateSubList(c){
return '<ul id="sublist" class="dropdown-menu">'+ c +'</ul>';
}
function CreateProductsList(){
return '<li class="dropdown"><ul id="productList" class="dropdown-menu">'+ c +'</ul></li>';
}
function HandleNoData(){
return '<li> Não existem categorias </li>';
}
function HandleNoSubData(){
return '<li> Não existem sub-categorias </li>';
}
function HandleNoProdData(){
return '<li> Não existem produtos </li>';
}
function GetCategorys(){
var url = base_url + 'home/ajaxCategorys';
$.post(url,function(js){
if (js != null && js != 'false')
BuildCategorys(JSON.parse(js));
else
return false;
});
}
function GetCategoryProducts(){
var url = base_url + 'home/ajaxCategoryProducts';
$.post(url,function(js){
if (js != null && js != 'false')
BuildProducts(JSON.parse(js));
else
return false;
});
}
$(document).ready(function(){
$('#menu-itex').on("click" ,function(e){
console.log('Click for menu');
$(this).next('ul').toggle();
e.stopPropagation();
e.preventDefault();
});
});
});
The output of my code directly as html it works but if i do in this way with JS script on generating it it doesn't trigger on menu-itex id click and i also tried by using the class. Got the trigger idea from w3wschools boostrap advanced menus.

When you add a event listener to a generated element before the item is generated (happens sometimes), it'll not trigger the event on click.
The best solution is to append the click event to body (or the item container that is rendered on page load) and listen to click only if it's inside the desired element.
It goes something like this:
//$('body').on('click', <-- would work too, but it's not delimited to a certain section of your page.
$('#category-content').on('click', '#menu-itex', function(){
//Your stuff here
})

Related

'DOMException: Failed to execute 'querySelectorAll' on 'Element' when using an 'option:selected' selector

I'm running a page which throws an error at the following line:
var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
For the sake of completeness, here is the full jQuery function (country-select.js):
(function($) {
$.fn.countrySelect = function (callback) {
$(this).each(function(){
var $select = $(this);
var lastID = $select.data('select-id'); // Tear down structure if Select needs to be rebuilt
if (lastID) {
$select.parent().find('span.caret').remove();
$select.parent().find('input').remove();
$select.unwrap();
$('ul#select-options-'+lastID).remove();
}
// If destroying the select, remove the selelct-id and reset it to it's uninitialized state.
if(callback === 'destroy') {
$select.data('select-id', null).removeClass('initialized');
return;
}
var uniqueID = Materialize.guid();
$select.data('select-id', uniqueID);
var wrapper = $('<div class="select-wrapper"></div>');
wrapper.addClass($select.attr('class'));
var options = $('<ul id="select-options-' + uniqueID +'" class="dropdown-content select-dropdown country-select"></ul>'),
selectChildren = $select.children('option, optgroup'),
valuesSelected = [],
optionsHover = false;
var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
// Function that renders and appends the option taking into
// account type and possible image icon.
var appendOptionWithIcon = function(select, option, type) {
// Add disabled attr if disabled
var disabledClass = (option.is(':disabled')) ? 'disabled ' : '';
var optgroupClass = (type === 'optgroup-option') ? 'optgroup-option ' : '';
var classes = option.attr('class');
var data = option.data('phone-code');
var opt = '<li class="' + disabledClass + optgroupClass + '"><span>';
if (option.val() !== '') {
opt += '<b class="flag flag-' + option.val().toLowerCase() + '"></b>';
}
opt += '<span class="option-label">' + option.html() + '</span>';
if (data && data !== '') {
opt += '<small>' + data + '</small>';
}
opt += '</span></li>';
options.append($(opt));
};
/* Create dropdown structure. */
if (selectChildren.length) {
selectChildren.each(function() {
if ($(this).is('option')) {
appendOptionWithIcon($select, $(this));
} else if ($(this).is('optgroup')) {
// Optgroup.
var selectOptions = $(this).children('option');
options.append($('<li class="optgroup"><span>' + $(this).attr('label') + '</span></li>'));
selectOptions.each(function() {
appendOptionWithIcon($select, $(this), 'optgroup-option');
});
}
});
}
options.find('li:not(.optgroup)').each(function (i) {
$(this).click(function (e) {
// Check if option element is disabled
if (!$(this).hasClass('disabled') && !$(this).hasClass('optgroup')) {
var selected = true;
options.find('li').removeClass('active');
$(this).toggleClass('active');
$newSelect.val($(this).find('.option-label').text());
activateOption(options, $(this));
$select.find('option').eq(i).prop('selected', selected);
// Trigger onchange() event
$select.trigger('change');
if (typeof callback !== 'undefined') callback();
}
e.stopPropagation();
});
});
// Wrap Elements
$select.wrap(wrapper);
// Add Select Display Element
var dropdownIcon = $('<span class="caret">▼</span>');
if ($select.is(':disabled'))
dropdownIcon.addClass('disabled');
// escape double quotes
var sanitizedLabelHtml = label.replace(/"/g, '"');
var $newSelect = $('<input type="text" class="select-dropdown" readonly="true" ' + (($select.is(':disabled')) ? 'disabled' : '') + ' data-activates="select-options-' + uniqueID +'" value="'+ sanitizedLabelHtml +'"/>');
$select.before($newSelect);
$newSelect.before(dropdownIcon);
$newSelect.after(options);
// Check if section element is disabled
if (!$select.is(':disabled')) {
$newSelect.data('constrainwidth', false)
$newSelect.dropdown({'hover': false, 'closeOnClick': false});
}
// Copy tabindex
if ($select.attr('tabindex')) {
$($newSelect[0]).attr('tabindex', $select.attr('tabindex'));
}
$select.addClass('initialized');
$newSelect.on({
'focus': function (){
if ($('ul.select-dropdown').not(options[0]).is(':visible')) {
$('input.select-dropdown').trigger('close');
}
if (!options.is(':visible')) {
$(this).trigger('open', ['focus']);
var label = $(this).val();
var selectedOption = options.find('li').filter(function() {
return $(this).find('.option-label').text().toLowerCase() === label.toLowerCase();
})[0];
activateOption(options, selectedOption);
}
},
'click': function (e){
e.stopPropagation();
}
});
$newSelect.on('blur', function() {
$(this).trigger('close');
options.find('li.selected').removeClass('selected');
});
options.hover(function() {
optionsHover = true;
}, function () {
optionsHover = false;
});
// Make option as selected and scroll to selected position
var activateOption = function(collection, newOption) {
if (newOption) {
collection.find('li.selected').removeClass('selected');
var option = $(newOption);
option.addClass('selected');
options.scrollTo(option);
}
};
// Allow user to search by typing
// this array is cleared after 1 second
var filterQuery = [],
onKeyDown = function(e){
// TAB - switch to another input
if(e.which == 9){
$newSelect.trigger('close');
return;
}
// ARROW DOWN WHEN SELECT IS CLOSED - open select options
if(e.which == 40 && !options.is(':visible')){
$newSelect.trigger('open');
return;
}
// ENTER WHEN SELECT IS CLOSED - submit form
if(e.which == 13 && !options.is(':visible')){
return;
}
e.preventDefault();
// CASE WHEN USER TYPE LETTERS
var letter = String.fromCharCode(e.which).toLowerCase(),
nonLetters = [9,13,27,38,40];
if (letter && (nonLetters.indexOf(e.which) === -1)) {
filterQuery.push(letter);
var string = filterQuery.join(''),
newOption = options.find('li').filter(function() {
return $(this).text().toLowerCase().indexOf(string) === 0;
})[0];
if (newOption) {
activateOption(options, newOption);
}
}
// ENTER - select option and close when select options are opened
if (e.which == 13) {
var activeOption = options.find('li.selected:not(.disabled)')[0];
if(activeOption){
$(activeOption).trigger('click');
$newSelect.trigger('close');
}
}
// ARROW DOWN - move to next not disabled option
if (e.which == 40) {
if (options.find('li.selected').length) {
newOption = options.find('li.selected').next('li:not(.disabled)')[0];
} else {
newOption = options.find('li:not(.disabled)')[0];
}
activateOption(options, newOption);
}
// ESC - close options
if (e.which == 27) {
$newSelect.trigger('close');
}
// ARROW UP - move to previous not disabled option
if (e.which == 38) {
newOption = options.find('li.selected').prev('li:not(.disabled)')[0];
if(newOption)
activateOption(options, newOption);
}
// Automaticaly clean filter query so user can search again by starting letters
setTimeout(function(){ filterQuery = []; }, 1000);
};
$newSelect.on('keydown', onKeyDown);
});
function toggleEntryFromArray(entriesArray, entryIndex, select) {
var index = entriesArray.indexOf(entryIndex),
notAdded = index === -1;
if (notAdded) {
entriesArray.push(entryIndex);
} else {
entriesArray.splice(index, 1);
}
select.siblings('ul.dropdown-content').find('li').eq(entryIndex).toggleClass('active');
// use notAdded instead of true (to detect if the option is selected or not)
select.find('option').eq(entryIndex).prop('selected', notAdded);
setValueToInput(entriesArray, select);
return notAdded;
}
function setValueToInput(entriesArray, select) {
var value = '';
for (var i = 0, count = entriesArray.length; i < count; i++) {
var text = select.find('option').eq(entriesArray[i]).text();
i === 0 ? value += text : value += ', ' + text;
}
if (value === '') {
value = select.find('option:disabled').eq(0).text();
}
select.siblings('input.select-dropdown').val(value);
}
};
$(function() {
$('.js-country-select').countrySelect();
});
$(document).on('change', '[data-country-select]', function() {
var target = 'select' + $(this).data('country-select');
var val = $(this).val();
var label = 'State';
var options = [
'<option value="" selected="" disabled="">Select State</option>'
];
if (val !== '') {
var country = window.__COUNTRIES[val];
var subdivisions = country.subdivisions;
var keys = Object.keys(subdivisions);
label = country.subdivisionName;
options = [
'<option value="" selected="" disabled="">Select ' + label + '</option>'
];
keys = keys.sort(function(a, b) {
var valA = subdivisions[a].toLowerCase();
var valB = subdivisions[b].toLowerCase();
if (valA < valB) return -1;
if (valA > valB) return 1;
return 0;
});
keys.forEach(function(key) {
options.push('<option value="' + key + '">' + subdivisions[key] + '</option>');
});
$(target).removeAttr('disabled');
} else {
$(target).attr('disabled', 'disabled');
}
$(target).parents('.input-field').find('label').html(label);
$(target).val('').html(options);
$(target).select2();
});
})(jQuery);
Here is the exception that I see in debug mode:
From what I understand from Failed to execute 'querySelectorAll' on 'Element' in ExtJS 5, :selected is not part of the CSS specification.
How should I fix this? Should I use:
var label = $select.find('option').filter(':selected').html() || $select.find('option').filter(':first').html() || "";
?
Converting Phil's comment to an answer, my debugger was set to pause on all exceptions (including caught ones). I had to de-activate the 'stop sign' button shown below to make the debugger work normally again.

Kendo Validator always says multi-select is invalid

I have a multiselect that is dynamically created and appended to a template with the following bit of code:
if(fieldMap[i].required == true){
extraString = '<div class="k-edit-label" style="margin-top: -6px;"><label for="'+fieldMap[i].fieldName+'Input">'+fieldMap[i].fieldLabel+'*</label>'+helpText+'</div>\n<div data-container-for="'+fieldMap[i].fieldName+'Input" class="k-edit-field" id="'+fieldMap[i].fieldName+'Container">\n';
dynamicComponent = '\t<input class="multiselect-binder" id="'+fieldMap[i].fieldName+'Input" name="'+fieldMap[i].fieldName.toLowerCase()+'" data-auto-close="false" data-role="multiselect" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" required data-required-msg="Please Select Valid '+fieldMap[i].fieldLabel+'" data-source="[';
//dynamicComponent = '\t<select id="'+fieldMap[i].fieldName+'Input" data-role="dropdownlist" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" required data-required-msg="Please Select Valid '+fieldMap[i].fieldLabel+'">';
} else{
extraString = '<div class="k-edit-label" style="margin-top: -6px;"><label for="'+fieldMap[i].fieldName+'Input">'+fieldMap[i].fieldLabel+'</label>'+helpText+'</div>\n<div data-container-for="'+fieldMap[i].fieldName+'Input" class="k-edit-field" id="'+fieldMap[i].fieldName+'Container">\n';
dynamicComponent = '\t<input class="multiselect-binder" id="'+fieldMap[i].fieldName+'Input" data-auto-close="false" data-role="multiselect" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" data-source="[';
//dynamicComponent = '\t<select id="'+fieldMap[i].fieldName+'Input" data-role="dropdownlist" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'">';
}
optString = '';
for(var k = 0; k < fieldMap[i].picklistVals.length; k++){
if(k == 0){
optString += '\''+fieldMap[i].picklistVals[k]+'\'';
}
else{
optString += ',\''+fieldMap[i].picklistVals[k]+'\'';
}
}
//Close the input component as well as the container div
dynamicComponent += optString + ']"/>\n<span class="k-invalid-msg" data-for="'+fieldMap[i].fieldName.toLowerCase()+'"></span></div>\n\n';
I run a validator.validate() on save button click to determine if information should be saved or not, which is dependent on if the multi-select input is required.
This pops up the invalid tooltip message when nothing is selected just fine. The issue is, however, that it will be marked invalid even if a selection is made. I am wondering if anyone has any solutions for how to get a validator to work correctly with the multiselect. Just hiding the pop ups is not really what I am after, as the validate() function will still fail even if the pop up is hidden, and I need the validate() function to pass.
Maybe not the best, but here is what I got.
function Save(){
$("#divTenureContainer .k-invalid").removeClass("k-invalid");
var tenureChecked = $("#chkTenure").prop('checked');
var tenureValid = Configuration_Tenure_Validator.validate();
}
Configuration_ValidateInput = (input) => {
var validationType = $(input).data("validation");
var required = $(input).prop("required") || $(input).hasClass("js-required");
if (!required) return true;
if (validationType) {
if (validationType === "stars") {
return $(input).val() > "0";
}
if (validationType === "hashtags") {
return ($(input).data("kendoMultiSelect").value().length > 0);
}
if (validationType === "required-text") {
return $(input).val() >= "";
}
}
return true;
}
var Configuration_ValidationRules = { rules: { Configuration_ValidateInput }, validationSummary: false };
var Configuration_Tenure_Validator = $("#divTenureContainer").kendoValidator(Configuration_ValidationRules).data("kendoValidator");

Js & Jquery:Understanding a search code with JSON request

i have a js search in my page that i don't get perfectly how does work because i don't know 100% js and jquery. As far as i think the code takes the input and search match with a link to a database that returns a JSON value depending on what name you put on the link (?name="the-input-name-here"), then, the code parse the json and determinates if the name of the input it's a valid surname and if it is the check if it has a running page, if it has redirects you to that page. If the input is a valid surname but doesn't have a running page it redirects you to "landing-page-yes.html". If the input isn't a valid surname it redirects you to "landing-page-no.html".
I need help to understand how the code does this in order to make a simplify version. How that call to another url database is parsed by the js ? How can i think something similar with a backend and ajax ? I need to understand 100% what this code does and i'm kinda lost.
THANKS !
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="srchid" width="100" onkeypress="submitonenter(document.getElementById('srchid').value, event, this)" />
<input onclick="nameCheck(document.getElementById('srchid').value);" value="CLICK HERE" type="button" style="background-color:#990033; color:#fff;border-style:outset;">
<div id="nameresults"></div>
<script >
<!--
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
} return false;
}
function cursor_wait() {
document.body.style.cursor = 'wait';
}
// Returns the cursor to the default pointer
function cursor_clear() {
document.body.style.cursor = 'default';
}
function nameCheck(sName) {
sName = trim(sName);
if(sName == ""){
alert("Please enter a name!");
return false;
}
cursor_wait();
routeToNameLookup(sName);
cursor_clear();
}
function $(id){return document.getElementById(id);}
// Get JSONP
function getJSON(url){
var s = document.createElement('script');
s.setAttribute('src',url);
document.getElementsByTagName('head')[0].appendChild(s);
}
function testcb(data){
//alert(data[0]);
}
function loaded(data) {
var name = document.getElementById('srchid').value;
var xmlhttp2;
//Using innerHTML just once to avoid multi reflow
$("nameresults").innerHTML = data[0];
if($("nameresults").innerHTML == 1){
if(data[1] == 1){
//display name page with content
var sNewName = name.replace (/'/g, ""); //remove any '
sNewName = removeSpaces(sNewName);
sNewName = convertNonAscii(sNewName);
//redirect to name crest
var sUrl = "http://www.heraldicjewelry.com/" + sNewName.toLowerCase() + "-crest-page.html";
//getJSON("http://www.gohapp.com/updatenamesearch.php?id=" + data[2] + "&pageurl=" + sUrl + "&callback=testcb");
//postwith(sUrl,{'pname':name});
window.location=sUrl;
} else {
//post to yes page
//postwith("http://www.heraldicjewelry.com/landing-page-yes.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-yes.html";
}
} else {
//post to no page
//postwith("http://www.heraldicjewelry.com/landing-page-no.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-no.html";
}
$("nameresults").innerHTML = "";
}
function routeToNameLookup(sSrchName) {
var name = document.getElementById('srchid').value;
if(sSrchName==""){
alert("Please enter your family name.");
} else {
var rn=Math.floor(Math.random()*1000000000000001)
getJSON("http://www.gohapp.com/namesearch_new.php?name="+name+"&rec=1&callback=loaded&rn="+rn);
}
}
function trim (sStr) {
var str = sStr.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
}
function postwith (to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
function removeSpaces(string) {
return string.split(' ').join('');
}
var PLAIN_ASCII =
"AaEeIiOoUu" // grave
+ "AaEeIiOoUuYy" // acute
+ "AaEeIiOoUuYy" // circumflex
+ "AaOoNn" // tilde
+ "AaEeIiOoUuYy" // umlaut
+ "Aa" // ring
+ "Cc" // cedilla
+ "OoUu" // double acute
;
var UNICODE =
"\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
+ "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
+ "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
+ "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
+ "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
+ "\u00C5\u00E5"
+ "\u00C7\u00E7"
+ "\u0150\u0151\u0170\u0171"
;
// remove accentued from a string and replace with ascii equivalent
function convertNonAscii(s) {
if (s == null)
return null;
var sb = '';
var n = s.length;
for (var i = 0; i < n; i++) {
var c = s.charAt(i);
var pos = UNICODE.indexOf(c);
if (pos > -1) {
sb += PLAIN_ASCII.charAt(pos);
} else {
sb += c;
}
}
return sb;
}
function submitonenter(name, evt,thisObj) {
evt = (evt) ? evt : ((window.event) ? window.event : "")
if (evt) {
// process event here
if ( evt.keyCode==13 || evt.which==13 ) {
thisObj.blur();
nameCheck(name);
//alert("looking for " + name);
}
}
}
//-->
</script>

Auto refresh a div containing Twitter posts

I am working with Twitter APIv1.1 and currently I am trying to implement a box which will display my latest tweets. This can be seen here:
http://www.jdiadt.com/twitterv1_1feed/testindex.html
However I would like to make this so that when I tweet, the box is automatically updated. I am quite new to JQuery and Javascript so I would appreciate any advice on how I can do this. I've hear AJAX can be used for something like this. Currently I have to refresh the entire page to display any new tweets. I'd like to only refresh the box.
Here is my script: twitterfeed.js
$(document).ready(function () {
var displaylimit = 10;
var twitterprofile = "jackcoldrick";
var screenname = "Jack Coldrick";
var showdirecttweets = false;
var showretweets = true;
var showtweetlinks = true;
var showprofilepic = true;
var headerHTML = '';
var loadingHTML = '';
headerHTML += '<a href="https://twitter.com/" ><img src="http://www.jdiadt.com/twitterv1_1feed/twitteroauth/images/birdlight.png" width="34" style="float:left;padding:3px 12px 0px 6px" alt="twitter bird" /></a>';
headerHTML += '<h1>'+screenname+' <span style="font-size:13px"><a href="https://twitter.com/'+twitterprofile+'" >#'+twitterprofile+'</a></span></h1>';
loadingHTML += '<div id="loading-container"><img src="http://www.jdiadt.com/twitterv1_1feed/twitteroauth/images/ajax-loader.gif" width="32" height="32" alt="tweet loader" /></div>';
$('#twitter-feed').html(headerHTML + loadingHTML);
$.getJSON('http://www.jdiadt.com/twitterv1_1feed/get_tweets.php',
function(feeds) {
//alert(feeds);
var feedHTML = '';
var displayCounter = 1;
for (var i=0; i<feeds.length; i++) {
var tweetscreenname = feeds[i].user.name;
var tweetusername = feeds[i].user.screen_name;
var profileimage = feeds[i].user.profile_image_url_https;
var status = feeds[i].text;
var isaretweet = false;
var isdirect = false;
var tweetid = feeds[i].id_str;
//If the tweet has been retweeted, get the profile pic of the tweeter
if(typeof feeds[i].retweeted_status != 'undefined'){
profileimage = feeds[i].retweeted_status.user.profile_image_url_https;
tweetscreenname = feeds[i].retweeted_status.user.name;
tweetusername = feeds[i].retweeted_status.user.screen_name;
tweetid = feeds[i].retweeted_status.id_str
isaretweet = true;
};
//Check to see if the tweet is a direct message
if (feeds[i].text.substr(0,1) == "#") {
isdirect = true;
}
//console.log(feeds[i]);
if (((showretweets == true) || ((isaretweet == false) && (showretweets == false))) && ((showdirecttweets == true) || ((showdirecttweets == false) && (isdirect == false)))) {
if ((feeds[i].text.length > 1) && (displayCounter <= displaylimit)) {
if (showtweetlinks == true) {
status = addlinks(status);
}
if (displayCounter == 1) {
feedHTML += headerHTML;
}
feedHTML += '<div class="twitter-article">';
feedHTML += '<div class="twitter-pic"><a href="https://twitter.com/'+tweetusername+'" ><img src="'+profileimage+'"images/twitter-feed-icon.png" width="42" height="42" alt="twitter icon" /></a></div>';
feedHTML += '<div class="twitter-text"><p><span class="tweetprofilelink"><strong><a href="https://twitter.com/'+tweetusername+'/status/'+tweetid+'">'+relative_time(feeds[i].created_at)+'</span><br/>'+status+'</p></div>';
feedHTML += '</div>';
displayCounter++;
}
}
}
$('#twitter-feed').html(feedHTML);
});
//Function modified from Stack Overflow
function addlinks(data) {
//Add link to all http:// links within tweets
data = data.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
return '<a href="'+url+'" >'+url+'</a>';
});
//Add link to #usernames used within tweets
data = data.replace(/\B#([_a-z0-9]+)/ig, function(reply) {
return '<a href="http://twitter.com/'+reply.substring(1)+'" style="font-weight:lighter;" >'+reply.charAt(0)+reply.substring(1)+'</a>';
});
return data;
}
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
var shortdate = time_value.substr(4,2) + " " + time_value.substr(0,3);
delta = delta + (relative_to.getTimezoneOffset() * 60);
if (delta < 60) {
return '1m';
} else if(delta < 120) {
return '1m';
} else if(delta < (60*60)) {
return (parseInt(delta / 60)).toString() + 'm';
} else if(delta < (120*60)) {
return '1h';
} else if(delta < (24*60*60)) {
return (parseInt(delta / 3600)).toString() + 'h';
} else if(delta < (48*60*60)) {
//return '1 day';
return shortdate;
} else {
return shortdate;
}
}
});
This is the get_tweets.php script where I encode the results in a JSON format.
<?php
session_start();
require_once('twitteroauth/twitteroauth/twitteroauth.php');
$twitteruser = "jackcoldrick";
$notweets = 30;
$consumerkey="xxxxxxxxxxxxxx";
$consumersecret="xxxxxxxxxxxxxxx";
$accesstoken="xxxxxxxxx";
$accesstokensecret="xxxxxxxxxxxxxx";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret){
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
echo json_encode($tweets);
?>
This seems doable with your current code. Things to consider:
I'm not sure, but Twitter might have a limit on requests (I imagine it's not a huge one)
Just encapsulate the reusable parts of your code in a function called updateTweets, and call that with a setInterval. There isn't anyway to really "push" tweet updates to your JavaScript, that I know of.
I would put your update code into a function that has a SetTimeout() that does a recursive call to the new function every x seconds. An example below.
$(document).ready(function () {
// Call to your update twitter function
updateTwitter(data);
});
function updateTwitter(data) {
// do your original update twitter GET
$.getJSON('http://www.jdiadt.com/twitterv1_1feed/get_tweets.php', function () {
//... all that code
});
// Sets a timer that calls the updateTwitter function 1x a minute
setTimeout(function () { updateTwitter(data); }, 60000);
}

Text area validation in javascript for html image tag

I want to validate a text area for img tag when it is duplicated. example, if i entered the image tag with src i should enter the same source with tag again i need to show alert how it could be done. my snippet to check whether the image is there or not. but i need to do for above validation also...
function validateEditor() {
var editor_val = $('#asset_html').val(), iSrc;
// Check for empty string
if(!string_IsEmpty(editor_val)) {
// Check whether img is available
if(editor_val.match(/img/g)) {
var src_cnt = (editor_val.match(/img/g).length);
//console.log(editor_val.match(/src/g).length);
$('#asset_html_preview').html(editor_val);
for(var j = 1; j <= src_cnt; j++) {
if($('#asset_html_preview img:nth-child(1)').attr('src')) {
iSrc = $('#asset_html_preview img:nth-child(1)').attr('src');
if(iSrc.indexOf('http://') != -1) {
$('#asset_html_preview img:nth-child(' + j + ')')
.error(function() { alert('Check ur image src'); });
//break;
}
}
}
}
}
}
You may be looking for this:
var arr = {};
var $div = $('<div />').html($('textarea').val());
$div.find('img').each(function (i) {
var src = $(this).attr('src');
if (src.indexOf('http://') >= 0 && arr[src] == undefined) {
arr[src] = 'foobar';
} else if (arr[src] !== undefined) {
alert('This url `' + src + '` already exists');
} else {
alert('This url `' + src + '` is wrong');
}
});
Demo: http://jsfiddle.net/LXgWU/3/
Assuming that your var src_cnt work perfect.
var src_cnt = (editor_val.match(/img/g).length);
if(src_cnt == 1)
{
alert("Plz choose Unique Image");
return false;
}

Categories