Jquery .click event doesn't fire what could be the cause? - javascript

I have the following jquery script in a Razor view with layout set to the null.
<script type="text/javascript">
jQuery(document).ready(function () {
$('#shareapp').click(function () {
check_if_fb_is_defined();
});
window.fbactivity_id = '#Model.Id';
window.fbactivity_name = 'your-hollywood-movie';
window.wallpost_name = 'How would be your hollywood movie poster look like ?';
window.wallpost_picture = '#ViewBag.ImageURL';
window.wallpost_description = 'How would be your hollywood movie poster look like?';
window.wallpost_link = '#Html.Raw(string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority,Url.Action("campaign_result", "facebook", new { #resultid = Model.Id, #imgURL = ViewBag.ImageURL })))';
window.wallpost_caption = 'Ozhay';
window.tags = 'Naser';
function check_if_fb_is_defined() {
if (typeof (FB) === 'undefined') {
fbsharer();
} else {
PostShare('#Html.Raw(string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority,Url.Action("campaign_result", "facebook", new { #resultid = Model.Id, #imgURL = ViewBag.ImageURL})))';
}
}
function PostShare(mylink) {
FB.ui({
method: 'share',
href: mylink,
hashtag: '#Ozhay',
}, function (response) {
if (response && !response.error_message) {
ga('send', 'event', 'Wallpost', 'Facebook', window.fbactivity_name, window.fbactivity_id);
} else {
ga('send', 'event', 'Wallpost', 'No', window.fbactivity_name, window.fbactivity_id);
}
});
}
//if FB is undefined
function fbsharer() {
ga('send', 'event', 'Dialog', 'Facebook', window.fbactivity_name, window.fbactivity_id);
window.fb_sharer_url = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(window.wallpost_link);
window.popupWindow = window.open(window.fb_sharer_url, 'facebooksharer', 'height=567,width=572');
var popupTimer = window.setInterval(function () {
if (typeof window.popupWindow !== 'undefined') {
if (window.popupWindow.closed !== false) {
window.clearInterval(popupTimer);
}
}
}, 200);
}
})
</script>
I have added Jquery script file to the view but for whatever reason When I click on a link that has shareapp id nothing happens. This is a bit strange to me where sometimes before it worked. your thoughts about this?

FB is undefined - where do you declare FB?
function check_if_fb_is_defined() {
if (typeof (FB) === 'undefined') {
fbsharer();
} else {
Syntax error - Need ')' before ';' at end of PostShare.
PostShare('#Html.Raw(string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority,Url.Action("campaign_result", "facebook", new { #resultid = Model.Id, #imgURL = ViewBag.ImageURL})))';
}
}
})

Related

href javascript button not showing

I am implementing a share function in my javascript. but the button link doesn’t appear, I’m really a beginner and researched but I couldn’t find out where I’m wrong, the button link just doesn’t appear, there’s no error log on my console. I am really lost if someone can help me I am grateful.
Before opening this question, I saw all the questions related to the same problem, but none were successful in my case.
$(document).ready(function() {
function sharefbimage() {
FB.init({ appId: `XXXXXX`, status: true, cookie: true });
FB.ui(
{
method: `share`,
name: 'Facebook Dialogs',
href: $(location).attr('href'),
link: 'https://developers.facebook.com/docs/dialogs/',
picture: 'your image url',
caption: 'Ishelf Book',
description: 'your description'
},
function (response) {
if (response && response.post_id) {
alert('success');
} else {
alert('error');
}
}
)};
$(".result").on("click", function() {
var id = $(this).attr("data-linkId");
var url = $(this).attr("href");
if(!id) {
alert("data-linkId attribute not found");
}
increaseLinkClicks(id, url);
return false;
});
var grid = $(".imageResults");
grid.on("layoutComplete", function() {
$(".gridItem img").css("visibility", "visible");
});
grid.masonry({
itemSelector: ".gridItem",
columnWidth: 200,
gutter: 5,
isInitLayout: false
});
$("[data-fancybox]").fancybox({
caption : function( instance, item ) {
var caption = $(this).data('caption') || '';
var siteUrl = $(this).data('siteurl') || '';
var sharefbimage = $(this).data('siteurl') || '';
if ( item.type === 'image' ) {
caption = (caption.length ? caption + '<br />' : '')
+ 'View image<br>'
+ 'Visit page';
+ 'share';
}
return caption;
},
afterShow : function( instance, item ) {
increaseImageClicks(item.src);
}
});
Try this.
if ( item.type === 'image' ) {
caption = (caption.length ? caption + '<br />' : '')
+ 'View image<br>'
+ 'Visit page<br>'
+ 'Share';
}

Backbone subview is not rendered, "Uncaught ReferenceError: view is not defined" error returned

I am working on a site that uses Backbone.js, jQuery and I am trying to render a subview that has to display a description of the current page, loaded depending on a choice made from a dropdown menu. I searched for more info in the web but I am still stuck on this. Please help!
Here is the main view in which I have to load the description view:
const InquiryContentView = Backbone.View.extend(
{
el: $('#inquiryContent'),
events: {
'change #styles': 'renderTabs',
'click li.tab': 'renderTabPanel'
},
initialize: function () {
const view = this
this.inquiryContent = new InquiryContent
this.inquiryContent.fetch(
{
success: function () {
view.listenTo(view.inquiryContent, 'update', view.render)
view.render()
}
})
},
render: function () {
const data = []
this.inquiryContent.each(function (model) {
const value = {}
value.id = model.id
value.text = model.id
value.disabled = !model.get('active')
data.push(value)
})
data.unshift({id: 'none', text: 'Select One', disabled: true, selected: true})
this.$el.append('<h2 class="pageHeader">Inquiry Content</h2>')
this.$el.append('<select id="styles"></select>')
this.$stylesDropdown = $('#styles')
this.$stylesDropdown.select2(
{
data: data,
dropdownAutoWidth: true,
width: 'element',
minimumResultsForSearch: 10
}
)
this.$el.append('<div id="navWrapper"></div>')
this.$el.append('<div id="tNavigation"></div>')
this.$navWrapper = $('#navWrapper')
this.$tNavigation = $('#tNavigation')
this.$navWrapper.append(this.$tNavigation)
this.$el.append('<div id="editorDescription"></div>')
},
renderTabs: function (id) {
const style = this.inquiryContent.findWhere({id: id.currentTarget.value})
if (this.clearTabPanel()) {
this.clearTabs()
this.tabsView = new TabsView({style: style})
this.$tNavigation.append(this.tabsView.el)
}
},
renderTabPanel (e) {
const tabModel = this.tabsView.tabClicked(e.currentTarget.id)
if (tabModel && this.clearTabPanel()) {
this.tabPanel = new TabPanelView({model: tabModel})
this.$tNavigation.append(this.tabPanel.render().el)
}
},
clearTabs: function () {
if (this.tabsView !== undefined && this.tabsView !== null) {
this.tabsView.remove()
}
},
clearTabPanel: function () {
if (this.tabPanel !== undefined && this.tabPanel !== null) {
if (this.tabPanel.dataEditor !== undefined && this.tabPanel.dataEditor.unsavedChanges) {
if (!confirm('You have unsaved changes that will be lost if you leave the page. '
+ 'Are you sure you want to leave the page without saving your changes?')) {
return false
}
this.tabPanel.dataEditor.unsavedChanges = false
}
this.tabPanel.remove()
}
return true
}
}
)
I am trying to render the subview adding this method:
renderDescription () {
this.$editorDescription = $('#editorDescription')
this.descView = new DescView({model: this.model})
this.$editorDescription.append(this.descView)
this.$editorDescription.html(DescView.render().el)
}
It has to be rendered in a div element with id='editorDescription'
but I receive Uncaught ReferenceError: DescView is not defined
Here is how DescView is implemented:
window.DescView = Backbone.View.extend(
{
el: $('#editorDescription'),
initialize: function () {
_.bindAll(this, 'render')
this.render()
},
render: function () {
$('#editorDescriptionTemplate').tmpl(
{
description: this.model.get('description')})
.appendTo(this.el)
}
);
What am I doing wrong?
Your implementation of the DescView is incomplete. You are missing a bunch of closing braces and brackets. That's why it's undefined.

Integrating Braintree Client token into braintree.client.create

I have limited experience working with JavaScript and am attempting to pass a client token generated on my server into the braintree client create of Braintree's javascript code. I do not know how to pass the ClientToken out of the jQuery post and into the authorization section of braintree.client.create. A portion of my code is below:
<script src="https://js.braintreegateway.com/web/3.34.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.34.0/js/hosted-fields.min.js"></script>
<script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>
<script src="https://js.braintreegateway.com/web/3.34.0/js/paypal-checkout.min.js"></script>
<script>
var form = document.querySelector('#register-form');
var submit = document.querySelector('input[type="submit"]');
var ClientToken;
var authPosting = jQuery.post('/path/to/php_scripts/getClientToken.php');
authPosting.done(function( data ) {
ClientToken = data;
console.log(ClientToken);
});
braintree.client.create({
authorization: 'ClientToken'
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '15px',
'font-family': 'roboto, verdana, sans-serif',
'font-weight': 'lighter',
'color': 'black'
},
':focus': {
'color': 'black'
},
'.valid': {
'color': 'black'
},
'.invalid': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: ''
},
cvv: {
selector: '#cvv',
placeholder: ''
},
expirationDate: {
selector: '#expiration-date',
placeholder: 'MM/YY'
},
postalCode: {
selector: '#postal-code',
placeholder: ''
}
}
}, function(err, hostedFieldsInstance) {
if (err) {
console.error(err);
return;
}
function findLabel(field) {
return jQuery('.hosted-field--label[for="' + field.container.id + '"]');
}
hostedFieldsInstance.on('focus', function (event) {
var field = event.fields[event.emittedBy];
findLabel(field).addClass('label-float').removeClass('filled');
jQuery(".error-msg").hide();
});
// Emulates floating label pattern
hostedFieldsInstance.on('blur', function (event) {
var field = event.fields[event.emittedBy];
var label = findLabel(field);
if (field.isEmpty) {
label.removeClass('label-float');
} else if (field.isValid) {
label.addClass('filled');
} else {
label.addClass('invalid');
}
});
hostedFieldsInstance.on('empty', function (event) {
var field = event.fields[event.emittedBy];
findLabel(field).removeClass('filled').removeClass('invalid');
});
hostedFieldsInstance.on('validityChange', function (event) {
var field = event.fields[event.emittedBy];
var label = findLabel(field);
if (field.isPotentiallyValid) {
label.removeClass('invalid');
} else {
label.addClass('invalid');
}
});
//Submit function
jQuery("#register-form").validate({
submitHandler: function(form) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (err, payload) {
if (err) {
if (err.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {
var msg = "All credit card fields are required.";
jQuery(".error-msg").text(msg);
jQuery(".error-msg").show();
} else if (err.code === 'HOSTED_FIELDS_FIELDS_INVALID') {
var invalidFields = err.details.invalidFieldKeys;
invalidFields.forEach(function (field) {
if (field == "number") {
var myid = "card-number";
var myobj = "credit card number";
} else if (field == "expirationDate") {
var myid = "expiration-date";
var myobj = "expiration date";
}
jQuery("#" + myid).append("<div class='error-msg'>Please enter a valid " + myobj + ".</div>");
});
} else {
var msg = "There was an error on the form."
alert (msg);
}
return;
}
vfirst = jQuery( "input#firstname" ).val(),
vlast = jQuery( "input#lastname" ).val(),
vemail = jQuery( "input#email" ).val(),
vproof = jQuery( "input[name='proof']" ).val(),
vprice = jQuery( "tr#total td.price" ).data('price'),
vcourse = 1950,
vnonce = 'fake-valid-nonce',
url = '/path/to/php_scripts/placeOrder.php';
// This is where you would submit payload.nonce to your server
// alert('Submit your cc nonce to your server here!');
});
//form.submit();
}
});
});
....more code below....
</script>
Any suggestions would be greatly appreciated.
Answering my own question:
CLIENT_AUTHORIZATION = jQuery.parseJSON(jQuery.ajax({
url: "/path/to/php_scripts/TokenScript.php",
dataType: "json",
async: false
}).responseText);
braintree.client.create({
authorization: CLIENT_AUTHORIZATION.token
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
} code continues.....
The CLIENT_AUTHORIZATION.token is whatever the token was named on the client authorization script.

can not find out if the div element is already set in body in chrome extension

in my chrome extension I got an div, which I will add to the body of the current tab. I am listening to chrome.tabs.onUpdated. If this event is called, I execute a script inside content_scripts. In this function there I´ll wait till the document is ready with jQuery $(document).ready(...).
I try to access
$("#div").length
and sometimes it returns 1 and sometimes 0. It should added to the body, if it´s not already there.
For some strange reasons, the onUpdated event is called twice on each page reload. Actually I found no way to check safely if the div was already added.
Edit: My Code:
inject.js:
var crendentials;
var mailInfo;
function doLogin(username, password)
{
function verifyLogin(username, password)
{
$.get("www.example.com&login&username=" + username + "&password=" + password,
function (data)
{
if (!isNaN($.trim(data)))
{
crendentials = new Array();
crendentials[0] = username;
crendentials[1] = password;
chrome.storage.sync.set({ key: "example_toolbar", value: username + ";;;" + password});
chrome.storage.sync.set({ key: "example_toolbar_verified", value: 1});
}
else
{
chrome.storage.sync.set({ key: "example_toolbar_verified", value: 0});
}
}
);
}
if (typeof username === "undefined" || username === null || username === ""
|| typeof password === "undefined" || password === null || password === "")
{
var crentest;
chrome.storage.sync.get("example_toolbar",
function (value)
{
console.log("value von doLogin()", value.example_toolbar);
crentest = value.example_toolbar;
}
);
if (typeof crentest !== "undefined" && crentest !== null && crentest !== "")
{
chrome.storage.sync.get("example_toolbar",
function (value)
{
crendentials = value.example_toolbar.split(";;;");
}
);
}
}
else
{
verifyLogin(username, password);
}
}
function getMailInfos(callback)
{
if (typeof mailInfo === "undefined")
{
$.get("http://www.example.com&mailapi=showmails",
function (data)
{
mailInfo = new Array();
var infos = data.split("|");
mailInfo.unread = infos[0];
mailInfo.total = infos[1];
callback();
}
);
}
else
{
callback();
}
}
function getMails(callback)
{
if (typeof mailInfo === "undefined")
{
getMailInfos(function ()
{
callback(mailInfo.unread);
}
);
}
else
{
callback(mailInfo.unread);
}
}
function renderText(textstr)
{
var divText = document.createElement("div");
addClass(divText, "toolbarText");
var text = document.createTextNode(textstr);
divText.appendChild(text);
toolbar.appendChild(divText);
}
var mailAmountDiv;
function renderMail(callback)
{
var mailIco = document.createElement("div");
addClass(mailIco, "mailIcon");
mailAmountDiv = document.createElement("div");
mailAmountDiv.id = "mails_unread";
addClass(mailAmountDiv, "mailAmount");
mailIco.appendChild(mailAmountDiv);
getMails(function (value)
{
var mailAmount = document.createTextNode(value);
mailAmountDiv.appendChild(mailAmount);
toolbar.appendChild(mailIco);
renderPlaceholderSmall();
renderText(translations.notAttended + ": " + getNotRead());
}
);
}
function createToolbar(change)
{
$(document).ready(function()
{
console.log("ist vorhanden: ", $("#Example-Toolbar").length);
if ($("#Example-Toolbar").length > 0)
{
// already created, stop working here
return;
}
doLogin();
toolbar = document.createElement("div");
toolbar.id = "Example-Toolbar";
renderMail(function()
{
renderPlaceholderLarge();
renderSearch();
renderPlaceholderSmall();
renderRightIcons();
$("body").css({"margin-top": "23px", "z-index": -1});
//document.body.insertBefore(toolbar, document.body.childNodes[0]);
$(toolbar).prependTo("body");
}
);
}
);
}
background.js:
function tabListener(tabId, changeInfo, tab)
{
// exec script on current focused tabId
chrome.tabs.executeScript(tabId,
{
code: 'createToolbar();'
}
);
}
chrome.tabs.onUpdated.addListener(tabListener);
manifest.json (only neccessary parts):
"background": {
"scripts": [
"background.js"
]
},
"permissions": [
"tabs",
"http://*/",
"https://*/",
"file:///*/*",
"storage"
],
"content_scripts": [{
"matches": ["*://*/*"],
"css": ["jquery-ui.css", "style.css"],
"js": ["jquery-2.0.3.min.js", "jquery-ui.min.js", "inject.js"],
"run_at": "document_start"
}]

Uncaught TypeError: Cannot call method 'observe' of null / Uncaught ReferenceError: Draggable is not defined

I've been all over the related questions but couldn't find an answer to my problem.
http://s1308.hizliresim.com/1d/5/r50lw.png
When I click "Kredi Yükle" a popup should appear but nothing happens and i get these console errors.
What should i do?
In related js file :
CreditLoadingAmrEditor = Class.create({
SELECTION_WINDOW : "wndCreditLoadingHelper",
BUTTON_OK : "btnLoadCreditOk",
BUTTON_CANCEL : "btnLoadCreditCancel",
CREDIT_AMOUNT : "fld_credit_amount",
initialize: function(owner) {
this.owner = owner;
this.browser = owner.browser;
this.buttonOk = $(this.BUTTON_OK);
this.buttonCancel = $(this.BUTTON_CANCEL);
this.selectionWindow = this.initializeHelper(this.SELECTION_WINDOW);
var containers = $$("div[id='loadingCreditContainer']");
if (containers && containers.size() > 0) {
this.container = containers[0];
this.editorManager = new EditorManager("loadingCreditContainer");
this.creditAmount = $(this.CREDIT_AMOUNT).instance;
}
this.browser.addToolClickListener(this);
this.buttonOk.observe(iconstants.KEY_CLICK, this.okClick.bindAsEventListener(this));
this.buttonCancel.observe(iconstants.KEY_CLICK, this.closeClick.bindAsEventListener(this));
},
initializeHelper: function(windowName) {
var result = $(windowName);
if (result){
result.remove();
document.body.appendChild(result);
}
return result;
},
toolClick: function(browser, toolType) {
if (toolType == browser.TOOL_LOAD_CREDIT) {
this.show();
}
return false;
},
show: function(callback) {
this.callback = callback;
FSystem.registerWindow(this.selectionWindow, true, true);
},
hide: function() {
FSystem.unregisterWindow(this.selectionWindow);
},
okClick: function() {
if (this.creditAmount.getValue() >= 0) {
this.hide();
this.requestForLoadingCredit();
} else {
window.alert(localize("value_must_greater_than_0"));
}
},
closeClick: function() {
this.hide();
},
requestForLoadingCredit: function() {
FSystem.startWait();
new Ajax.Request(
iconstants.URL_CREDIT_LOADING_AMR,
{
method : iconstants.METHOD_POST,
parameters : {mid:this.browser.getSelectedId(),ca:this.creditAmount.getValue()},
onComplete : this.responseForDeviceReading.bind(this),
onException : null
});
},
responseForDeviceReading: function(transport) {
FSystem.stopWait();
var JSON = transport.responseText.evalJSON();
if (JSON.status == iconstants.AJAX_STATUS_OK){
//if (confirm(JSON.message)) {
window.open(JSON.url, '_newtab', 'width=1280,height=800');
//}
} else {
alert(JSON.message);
}
}
});
Such type of error occur when your object is not initialized. You are trying to access a method of such object which is not initialized. Please check your object initialization.

Categories

Resources