Using javascript object to call function and virables - javascript

Am trying to advance my javascript code, by using it as an object so i can call it when needed but it doesn't work. Please can someone help me out i will appreciate it.
var AppObject = {
var targetElement = "#AjaxLoadBodyContentLoader";
init: function (hashUrl, defaultBack){
if(hashUrl != defaultBack && hashUrl != ""){
var LoadHashUrl = hashUrl+' #AjaxLoadBodyContentLoader';
$('#AjaxLoadBodyContentLoader').load(
LoadHashUrl,
{"async_content" : "true", "PrevLink" : defaultBack}
);
}
},
asyncShowContent: function(){
/*$.getScript("external.js");*/
$(this.targetElement).show('normal', this.asyncPregressBar);
},
asyncPregressBar: function(){
$('#preloader').fadeOut();
$('#status').fadeOut();
},
asyncLoader: function(){
$(this.targetElement).load(
this.linkPath,
{"async_content" : "true", "PrevLink" : this.PrevLink},
function(responseTxt, statusTxt, xhr){
this.asyncShowContent();
console.log("Status: " + xhr.status + " | Text: " + xhr.statusText);
}
);
},
asyncExtecute: function(e){
var targetUrl = e.target.href;
if(typeof targetUrl == 'undefined' || targetUrl == ""){
targetUrl = $(this).attr('href');
}
var linkPath = targetUrl + ' ' + this.targetElement;
var PrevLink = $(this).attr('data-page-link');
window.location.hash = targetUrl;
$('#preloader').fadeIn();
$('#status').fadeIn();
$(this.targetElement).hide('fast',this.asyncLoader);
}
}
Using the above code without adding it inside AppObject={}, work very fine, but i want to advance it and learn more how to use javascript object.
Usage
$(function(){
AppObject.init(
window.location.hash.substr(1),
location.href.replace(location.hash,"")
);
$(document).on('click', 'a.LoadPage', function(e){
AppObject.asyncExtecute(e);
});
});

As #musefan says in a comment, you have a syntax problem:
This is wrong:
var AppObject = {
var targetElement = "#AjaxLoadBodyContentLoader";
...
}
This is a variable declaration:
var targetElement = "#AjaxLoadBodyContentLoader";
Inside an object, you need to use key/value pairs:
var AppObject = {
targetElement : "#AjaxLoadBodyContentLoader",
...
}
EDIT: e is undefined
e should be your event, you need it in asyncExtecute,
var AppObject = {
asyncExtecute: function(e){
e.preventDefault(); // Add this line, to prevent the browser to immediately navigate to other window
var targetUrl = e.target.href;
...
}
}
$(function(){
...
$(document).on('click', 'a.LoadPage', function(e){
AppObject.asyncExtecute(e); // Here you are passing the event object to asyncExtecute
});
});

Problem is the way you are adding property to your object. Please add it as below:
var AppObject = {
targetElement: "#AjaxLoadBodyContentLoader",
//remaining code---
};

Related

Ajax call works only first time

This is my code, to modify the content of a table cell, clicking a link "Open/Close" of the sibling cell.
The link works good the first time but on the second click, the execution start again from
$("a[href*='close']").click(function (event)
even if the new link contains "open" and not the word "close" anymore.
Why have I this behaviour?
Which is the problem? How can I solve it?
Thanks in advance!
$(document).ready(function()
{
$("a[href*='close']").click(function (event)
{
event.preventDefault();
var click = $(this);
console.log(click);
var url = click.attr("href");
console.log(url);
var nid = url.split("/")[1];
console.log(nid);
// var url = "close/" + nid;
// console.log(url);
$.get(url, function(data, status)
{
if (data.status == 1)
{
console.log(data.res);
click.text("Open");
var new_url = url.replace("close", "open");
console.log("New Url = " + new_url);
click.attr("href", new_url);
click.parent().prev().text(data.res);
}
else
{
console.log("Error");
}
});
}); // CHIUDE FUNZIONE
$("a[href*='open']").click(function (event)
{
event.preventDefault();
var click2 = $(this);
console.log(click2);
var url = click2.attr("href");
console.log(url);
var nid = url.split("/")[1];
console.log(nid);
// var url = "open/" + nid;
// console.log(url);
$.get(url, function(data, status)
{
if (data.status == 1)
{
console.log(data.res);
click2.text("Close");
var new_url = url.replace("open", "close");
console.log("New Url = " + new_url);
click2.attr("href", new_url);
click2.parent().prev().text(data.res);
}
else
{
console.log("Error");
}
});
}); // CHIUDE FUNZIONE
As I stated in my comment to the question, you can use a delegate event binding, rather than juggling event bindings, to allow events to only be processed by the logic that you want them to be processed by.
$(document).on('click', 'a[href*="close"]', function (event) {
event.preventDefault();
console.log('close');
event.target.href = '#open';
});
$(document).on('click', 'a[href*="open"]', function (event) {
event.preventDefault();
console.log('open');
event.target.href = '#close';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Toggle

jQuery - preventDefault() in .each function

I want to use preventDefault() in .each function for collection of buttons and its not working. When I use it with one .click function it works fine but inside .each is not
Whan am I doing wrong?
Here is my .js code
$(document).ready(function() {
var findingStatus = $('#findingStatus').attr('finding-status-type');
var findingLike = $('#finding_like_btn');
var findingDislikeBox = $('.finding_dislike_add');
var findingDislikeCollection = $('.finding_dislike_add_btn')
var findingUnlike = $('#finding_unlike_btn');
var findingDislikeRemoved = $('#finding_dislike_removed');
var alertBox = $('.alert-box').hide();
if (findingStatus == 0) {
findingDislikeBox.show();
findingUnlike.hide();
findingDislikeRemoved.hide();
}
else if (findingStatus == 1) {
findingDislikeBox.hide();
findingUnlike.show();
findingDislikeRemoved.hide();
}
else if (findingStatus == 2) {
findingDislikeRemoved.show();
findingUnlike.show();
findingDislikeBox.hide();
findingLike.hide();
}
findingDislikeCollection.each(function() {
var findingDislike = $(this).clone();
var url = findingDislike.attr("href");
findingDislike.click(function(event) {
event.preventDefault();
$.ajax({
url: url,
type: "POST",
dataType: "json",
success: function(data) {
if (data.profileState == 1) {
$('#dislike_count_btn').text('Odrzuć' + data.DislikeCount);
findingDislikeBox.hide();
findingDislikeRemoved.show();
findingUnlike.show();
//findingUnDislike.show();
//findingUnDislike.attr('disabled', false );
//findingUnDislike.text('Cofnij');
}
else {
alertBox.show();
if ($('.alert-box-msg').length==0) {
$('.alert-area').prepend('<p class="alert-area alert-box-msg">Żeby korzystać z tej funkcji musisz być zalogowany.</p>');
}
findingDislike.attr('disabled', false );
}
},
error: function() {
alert('Problem z serwerem, spróbuj ponownie za kilka minut.');
findingDislike.attr('disabled', false );
}
});
});
});
$('html').click(function (e) {
if (!$(e.target).hasClass('alert-area')) {
$('.alert-box').hide();
findingDislike.attr('disabled', false );
}
});
});
Thanks for answer
You are cloning the element with .clone which means you're not actually attaching an event listener to anything in the DOM. Cloned elements must be manually inserted into the DOM with JavaScript for them to have any effect.
This is not a correct way. Following should work:
findingDislikeCollection.click(function(event){
var findingDislike = $(this);
var url = findingDislike.attr("href");
//AJAX call
event.preventDefault();
});
More details on click event are given here:
https://api.jquery.com/click/

Check if link contains javascript

How can I tell, in JavaScript/jQuery if a link is Javascript?
For example:
Trigger
Trying to make sure a script only logs links, and not javascript, anchors, etc.
Basically I need to capture the href of the link as I .each through them (already done) I just need a reliable way to check that variable to see if it is javascript, ie, function w/e
var rand = function() {
return Math.random().toString(36).substr(2);
};
$(function(){
$('#lhcb a').each(function() {
var rawlink = $(this).attr("href");
var link = encodeURIComponent( rawlink );
var token = rand();
var href = $(this).prop('href');
var proceed = $.get( "lhc/link.php?link=" + link + "&a=c", function( data ) {
if ( data == 1 ) {
return true;
} else {
return false;
}
});
if ( href.match("^javascript:") ) {
proceed = false;
}
if ( rawlink.charAt(0) != '#' ) {
if ( proceed ) {
$(this).after( " <span style='font-size:xx-small;'>( Hits: <span id='" + token + "'></span> )</span>" );
$.get( "lhc/link.php?link=" + link + "&a=q", function( data ) {
$('#' + token).html(data);
});
$(this).attr( "href", "lhc/link.php?link=" + link + "&a=g" );
}
}
});
});
This is what I have, but as mentioned below, it wouldn't be able to see if the href is just a function without the JavaScript declaration.
A little script can help. I wrote a sample:
http://jsfiddle.net/qXkHX/
var normalLinks = [];
$("a").each(function(i) {
var a = $(this);
var href = $.trim(a.attr("href"));
if(href.indexOf("javascript:") !== 0) normalLinks.push(href);
});
$("#result").text(normalLinks.join(","));
It iterates through the anchors in the document and pushes every link that does not start with javascript:. Maybe this helps.

how can I cause any change to a variable in an internal function to affect main variable value

I know java script doesn't have call by reference. So how can I solve this?
(function($){
$.fn.extend({
something: function(options) {
var Status;
var defaults = {
regex:/^([\u0600-\u06FF]|\s)*$/,
errortxt:"Invalid input",
emptytxt:"It should not be empty"
}
var options = $.extend(defaults, options);
$(this).bind('change', function () {
Status = true;
$(this).each(function() {
/*variables*/
var necessaryElement;
if (options.regex && options.errortxt && options.errorsection)
{
var filter = options.regex;
var $this = $(this);
var wrongMessage = options.errortxt;
var $errordiv = $("[ID$="+options.errorsection+"]");
} else{
console.log("Error : Not enough arguments for invoking something Plugin");
}
if (options.emptytxt)
{
var noMessage = options.emptytxt;
necessaryElement = true;
}
else
{
necessaryElement = false;
}
var elementvalue = $this.val();
/* Methods */
if (elementvalue != "" && necessaryElement) {
if (filter.test(elementvalue)){
$this.removeClass("error").addClass("ok");
$errordiv.fadeOut(300);
} else {
Status = false;
$this.removeClass("ok").addClass("error");
$errordiv.fadeIn(200);
$errordiv.text(wrongMessage);
}
} else if (elementvalue == "" && necessaryElement) {
Status = false;
$this.removeClass("ok").addClass("error");
$errordiv.fadeIn(200);
$errordiv.text(noMessage);
}
});
});
return Status;
}
});
})(jQuery);
and I call it in another js in this way:
var myarray=new Array();
myarray[0] = $('#selector').something({
regex:/^([\u0600-\u06FF]|\s)*$/,
// another options
});
$('#selector').change(function (){
alert (myarray[0]);
});
but it alerts undefined.
If I change var Status to var Status= true Then it always alerts true.
Can anyone help me? How I can change the code to return the desired Status?
Edit : Trying to be clearer.
Something() returns a value which is modified by change.
So when you call something you return the value unmodified.
Then you call change that will change the value, but it's not passed by reference in the array so it won't change anything.
You may want to use the data function available on JQuery objects for keeping data.
Here is a simplified version:
(function($){
$.fn.extend({
something: function(options) {
$(this).bind('change', function () {
$(this).data('status','true');
});
}
});
})(jQuery);
$(document).ready(function() {
var myarray=new Array();
myarray[0] = $('#selector').something({
regex:/^([\u0600-\u06FF]|\s)*$/
});
$('#selector').change(function (){
alert ($(this).data('status'));
});
});

jQuery + Javascript: Consolidate duplicate functions between document.ready and ajax load

I am using the ajaxify.js plugin https://github.com/browserstate/ajaxify to load content dynamically.
I have a number of click functions that I bind on document ready, but have to additionally put those functions inside of my ajax load function to re-bind the click events to the newly added content. I had tried using a single set of live functions previously but they didn't work.
Anyway I have the following code twice, once inside of a document.ready(function(){ }) and once again inside of ajaxify.js after the content loads.
I know it's superfluous, but I'm not sure of how to go about writing the functions just once so I can "include" them elsewhere. How can I optimize these functions so I can consolidate them and use them over again in an efficient manner?
Thank you!
var $filterclear = $('.filters .filter-clear'),
filtercount = $filterclear.length,
$searchedfor = $('.searched-for'),
is_search = $searchedfor.length;
$filterclear.bind('click', function(){
var $me = $(this);
if(filtercount == 3) {
$('.clear-all.filter-clear').addClass('filter-out').fadeOut('fast');
$(this).addClass('filter-out').fadeOut('fast');
} else {
$(this).addClass('filter-out').fadeOut('fast');
}
if($me.hasClass('clear-all') || filtercount == 1) {
$filterclear.addClass('filter-out').fadeOut('fast');
if(is_search !== 0) {
$('.filters').fadeOut();
}
}
});
$('.tag.remove-term').bind('click', function(){
var $me = $(this),
mytext = $me.text(),
$myfilter = $('.filters .filter-clear:contains("'+ mytext +'")');
if(filtercount == 3) {
$('.clear-all.filter-clear').addClass('filter-out').fadeOut('fast');
$myfilter.addClass('filter-out').fadeOut('fast');
} else {
$myfilter.addClass('filter-out').fadeOut('fast');
}
});
$searchedfor.find('.filter-clear').bind('click',function(){
$searchedfor.fadeOut();
});
Defining a new function should work (I didn't test it):
var $filterclear = $('.filters .filter-clear'),
filtercount = $filterclear.length,
$searchedfor = $('.searched-for'),
is_search = $searchedfor.length;
var doSomething($myfilter) {
if(filtercount == 3) {
$('.clear-all.filter-clear').addClass('filter-out').fadeOut('fast');
}
$myfilter.addClass('filter-out').fadeOut('fast');
};
$filterclear.bind('click', function() {
var $me = $(this);
doSomething($me);
if($me.hasClass('clear-all') || filtercount == 1) {
$filterclear.addClass('filter-out').fadeOut('fast');
if(is_search !== 0) {
$('.filters').fadeOut();
}
}
});
$('.tag.remove-term').bind('click', function(){
var $me = $(this),
mytext = $me.text(),
$myfilter = $('.filters .filter-clear:contains("'+ mytext +'")');
doSomething($me);
});
$searchedfor.find('.filter-clear').bind('click',function(){
$searchedfor.fadeOut();
});

Categories