Like or dislike function works only once as if "liked" variable is no more true or false, which would be valid values. First time it works fine (both like and dislike ), but second time 'else' alert appears, which is absolutely unclear to me. Could you please explain what may be wrong there? Bool in html is updated correctly as I checked via alert.
HTML with little django template code, don't pay attention :
<div class="incriminate_like" data-post-pk="{{ answer.pk }} " data-who-likes-id="{{ request.user.id }} " >
<div class="data_div" data-bool="false">
<img class="like_image" src="{% static "img/like.png" %}"/>
</div>
</div>
JQUERY:
$('.incriminate_like').click(function(){
var post_pk = $(this).data("post-pk");
var who_likes_id = $(this).data("who-likes-id");
var that = $(this);
var liked = $(this).find(".data_div").data("bool");
function makeLiked(){
that.find("img").attr("src","{% static 'img/likered.png' %}");
that.find(".data_div").data("bool","true");
// just incriminating
var like_number_original = that.next().html();
var integer_of_like_number_original = parseInt(like_number_original);
var plus_one_number = integer_of_like_number_original + 1
that.next().html(plus_one_number);
}
function makeDisliked(){
that.find("img").attr("src","{% static 'img/like.png' %}");
that.find(".data_div").data("bool","false");
// just incriminating
var like_number_original = that.next().html();
var integer_of_like_number_original = parseInt(like_number_original);
var plus_one_number = integer_of_like_number_original - 1
that.next().html(plus_one_number);
}
if (liked == false) {
ajaxPost('/like/', {'post_pk': post_pk,'who_likes_id':who_likes_id,'whom_id':whom_id}, function(){
makeLiked();
})
}
else if (liked == true ) {
ajaxPost('/dislike/', {'post_pk': post_pk,'who_likes_id':who_likes_id,'whom_id':whom_id}, function(){
makeDisliked();
})
}
else {
alert('error');
}
})
Problem is that if you call makeLiked() or makeDisliked(), you set data-bool value to string, so that's why liked == true (and even liked == false) returns simply false.
Try setting things like:
that.find(".data_div").data("bool", true);
(note that second parameter is without "")
So final code should like that:
$('.incriminate_like').click(function() {
var post_pk = $(this).data("post-pk");
var who_likes_id = $(this).data("who-likes-id");
var that = $(this);
var liked = $(this).find(".data_div").data("bool");
function makeLiked() {
that.find("img").attr("src", "{% static 'img/likered.png' %}");
that.find(".data_div").data("bool", true);
// just incriminating
var like_number_original = that.next().html();
var integer_of_like_number_original = parseInt(like_number_original);
var plus_one_number = integer_of_like_number_original + 1
that.next().html(plus_one_number);
}
function makeDisliked() {
that.find("img").attr("src", "{% static 'img/like.png' %}");
that.find(".data_div").data("bool", false);
// just incriminating
var like_number_original = that.next().html();
var integer_of_like_number_original = parseInt(like_number_original);
var plus_one_number = integer_of_like_number_original - 1
that.next().html(plus_one_number);
}
if (liked == false) {
ajaxPost('/like/', {
'post_pk': post_pk,
'who_likes_id': who_likes_id,
'whom_id': whom_id
}, function() {
makeLiked();
})
} else if (liked == true) {
ajaxPost('/dislike/', {
'post_pk': post_pk,
'who_likes_id': who_likes_id,
'whom_id': whom_id
}, function() {
makeDisliked();
})
} else {
alert('error');
}
})
Related
Is it possible to get some page arguments from an asp file in a js function ?
I'm kind of new to these technologies, and I was asked to migrate some old code, but I'm not sure if it's possible.
Here is what I got so far :
I have a file CommentsPage.aspx which contains a call to a conversation.html which contains a button :
<button type="button" class="plm-ImportMsgFiles-button btn bg-transparent border-0 p-0 ml-1"
title="ImportMsgFiles">
<svg class="plm-icon-sm plm-icon-green">
<use href="#do-remove-disc"></use>
</svg>
</button>
This button executes some js :
$(".plm-conversation").on("click", ".plm-ImportMsgFiles-button", function() {
// import msg file.
var commentPartGuid = $(this).closest(".plm-conversation-item")
.attr("data-plm-partguid");
ImportMsgFiles(commentPartGuid);
});
That js will call a CSIcmdImportMsgFiles.asp which contains some important calls to some code in C#. That same js code used to get some page arguments from this asp, but it's not working anymore. Here is the call to the asp and the call for the page arguments as it was :
The parameters are strCommandId for the command to execute in the asp, strCommandUrl for the url of the asp, callbackFunction for the function to execute at the end, and strFrameName is left blank.
Namespace.SendCommandImport = function (strCommandId, strCommandUrl, callbackFunction, strFrameName) {
if (!strFrameName) {
strFrameName = "oNamespaceCommandFrame";
}
if (callbackFunction) {
if (Namespace.RegisterCommand(strCommandId, callbackFunction)) {
var objCommandFrame = window.frames[strFrameName];
if (!objCommandFrame) {
Namespace.CreateFrameImport(strFrameName);
objCommandFrame = window.frames[strFrameName];
}
if (objCommandFrame) {
_isNamespaceCommandReady = true;
objCommandFrame.location.replace("Blank.asp");
objCommandFrame.location.replace(strCommandUrl);
}
}
}
}
Namespace.CreateFrameImport = function (strFrameName) {
var objCommandFrame = null;
if (_Browser.IsFirefox || _Browser.IsIE10OrLater || _Browser.IsChrome) {
objCommandFrame = document.createElement("iframe");
objCommandFrame.setAttribute("name", strFrameName);
}
else
objCommandFrame = document.createElement("<iframe name=\"" + strFrameName + "\" ></iframe>");
objCommandFrame.setAttribute("id", strFrameName);
objCommandFrame.setAttribute("src", "Blank.asp");
document.body.appendChild(objCommandFrame);
objCommandFrame.style.display = "none";
var loadHandler = function () {
Namespace.CommandDoneImport(strFrameName);
};
if (objCommandFrame.addEventListener) {
objCommandFrame.addEventListener("load", loadHandler, false);
} else {
objCommandFrame.attachEvent("onload", loadHandler);
}
}
Namespace.CommandDoneImport = function (strFrameName) {
var objCommandFrame = window.frames[strFrameName];
if (objCommandFrame != null) {
var str_location = objCommandFrame.location.toString();
if ((_isNamespaceCommandReady) && (str_location.indexOf("Blank.asp") < 0)) // Is there a command?
{
_isNamespaceCommandReady = false;
var str_command_id = objCommandFrame.window.GetCommandId();
var str_status = objCommandFrame.window.GetCommandStatus();
if (_NamespaceCommands != null) {
for (var i = 0; i < _NamespaceCommands.length; i++) {
var command = _NamespaceCommands[i];
if (command != null) {
if (command[0] == str_command_id) {
command[1](str_command_id, str_status, objCommandFrame);
break;
}
}
}
}
}
}
}
When i execute this code the methods objCommandFrame.window.GetCommandId() and objCommandFrame.window.GetCommandStatus() are not recognized as functions. They are both defined in CSIcmdImportMsgFiles.asp like so :
<script type="text/javascript">
var _strCommandId = "<%=strCommandId%>";
function GetCommandId() { return _strCommandId; }
</script>
With strCommandId being defined in the asp as dim strCommandId.
I will gladly provide more information as I am stuck on this issue.
Thanks in advance
I took this code from internet to modify, to practice JS, though I fail to call the function when the input length is equal 0. So basically I click on the "Add a column" and it opens the console to give the name of the column you want to make, though when the input length as I said is equal to 0, it raises and alert, but it doesn't ask again for the input (I don't know how to call the function so the input console will show up again).
Down below you have the JS code, for the whole code (html, css, js) click here.
function Column(name) {
if (name.length > 0) {
var self = this; // useful for nested functions
this.id = randomString();
this.name = name;
this.$element = createColumn();
function createColumn() {
var $column = $("<div>").addClass("column");
var $columnTitle = $("<h2>")
.addClass("column-title")
.text(self.name);
var $columnCardList = $("<ul>").addClass("column-card-list");
var $columnDelete = $("<button>")
.addClass("btn-delete")
.text("x");
var $columnAddCard = $("<button>")
.addClass("add-card")
.text("Add a card");
$columnDelete.click(function() {
self.removeColumn();
});
$columnAddCard.click(function(event) {
self.addCard(new Card(prompt("Enter the name of the card")));
});
$column
.append($columnTitle)
.append($columnDelete)
.append($columnAddCard)
.append($columnCardList);
return $column;
}
} else if (name.length == 0) {
alert("please type something");
} else {
return;
}
}
Column.prototype = {
addCard: function(card) {
this.$element.children("ul").append(card.$element);
},
removeColumn: function() {
this.$element.remove();
}
};
function Card(description) {
var self = this;
this.id = randomString();
this.description = description;
this.$element = createCard();
function createCard() {
var $card = $("<li>").addClass("card");
var $cardDescription = $("<p>")
.addClass("card-description")
.text(self.description);
var $cardDelete = $("<button>")
.addClass("btn-delete")
.text("x");
$cardDelete.click(function() {
self.removeCard();
});
$card.append($cardDelete).append($cardDescription);
return $card;
}
}
Card.prototype = {
removeCard: function() {
this.$element.remove();
}
};
var board = {
name: "Kanban Board",
addColumn: function(column) {
this.$element.append(column.$element);
initSortable();
},
$element: $("#board .column-container")
};
function initSortable() {
$(".column-card-list")
.sortable({
connectWith: ".column-card-list",
placeholder: "card-placeholder"
})
.disableSelection();
}
$(".create-column").click(function() {
var name = prompt("Enter a column name");
var column = new Column(name);
board.addColumn(column);
});
// ADDING CARDS TO COLUMNS
todoColumn.addCard(card1);
doingColumn.addCard(card2);
});
After the line:
alert("please type something");
Add the following:
$(".create-column").click();
That programmatically "clicks" the Create Column button.
If you want to prompt the user to enter column name if length is 0, just add this lines of code to your if-stament:
var name = prompt("Enter a column name");
var column = new Column(name);
board.addColumn(column);.
As shown below:
else if (name.length == 0) {
alert("please type something");
var name = prompt("Enter a column name");
var column = new Column(name);
board.addColumn(column);
} else {
return;
}
If that was your question, this should be able to fix it.
I want to learn how to write Jquery plugin.This is my normal function and convert it into jquery plugin could you suggest me how to do this.
So that I can easily understand how to convert function to the plugin.
function probe_Validity(element) {
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
}
Take a look at this project jQuery plugin boilerplate
Consider this as a base plugin definition, look it up, follow the steps and adjust them to your needs.
It's quite easy to do you just use
jQuery.fn.theNameOfYourFunction = function() {}
then you can get the element the function is called on like this :
var element = $(this[0])
so with your function it would be :
jQuery.fn.probe_Validity = function() {
var element = $(this[0]);
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
};
this can be called like so :
$('#id').probe_Validity ()
JavaScript is combining two seperate links and opening them in the same tab, which is a dead link.
Ex. If I tweet'Laser Blue' is now available http://swoo.sh/14F9swF pic.twitter.com/xb6Hm1UnX9, it will open a new tab, and go to http://swoo.sh/14F9swFpic.twitter.com/xb6Hm1UnX9, which is a dead link.
I'd like it to recognize both links, and open them in 2 seperate tabs.
Ex. Tab 1. ttp://swoo.sh/14F9swF Tab 2. pic.twitter.com/xb6Hm1UnX9.
NOTE: I Do NOT have the link before hand.Javascript has to detect the link.
This is the script. It is in backround.js.
Thankyou.
var req = new XMLHttpRequest();
function test() {
req.open(
"GET",
"https://api.twitter.com/1/statuses/user_timeline.json?screen_name=nikestore&count=1550&exclude_replies=true&trim_user=true",
true);
req.onload = showTweets;
req.send(null);
setTimeout(test, 3000);
}
function showTweets() {
var data = req.responseText;
var tweets = $.parseJSON(data);
$.each(tweets, function (data) {
var id = this.id;
var txt = this.text;
if(!txt) {
return false;
}
var link = txt.substring(txt.indexOf("http://"));
var lastTweet = localStorage["lastTweet"];
//var txt = txt.replace("\u2018", "").replace("\u2019", "");
var z = localStorage["keyword"];
if (txt.toLowerCase().indexOf("now available") >= 0 && id != lastTweet) {
if (localStorage["keyword"] && txt.indexOf(localStorage["keyword"]) >= 0) {
chrome.tabs.create({url:link});
localStorage["lastTweet"] = id;
return false;
}
}
else if (id == lastTweet)
{
return false;
}
});
}
chrome.extension.onRequest.addListener(
function (request, sender, sendResponse) {
if (request.command == "startCheck") {
setTimeout(test, 3000);
}
else if (request.command == "stopCheck") {
clearTimeout(test);
}
});
I am trying to create collapsible DIVs that react to links being clicked. I found how to do this using "next" but I wanted to put the links in a separate area. I came up with this which works...
JSFiddle - Works
function navLink(classs) {
this.classs = classs;
}
var homeLink = new navLink(".content-home");
var aboutLink = new navLink(".content-about");
var contactLink = new navLink(".content-contact");
var lastOpen = null;
$('.home').click(function() {
if(lastOpen !== null) {
if(lastOpen === homeLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-home').slideToggle('slow');
lastOpen = homeLink;
}
);
$('.about').click(function() {
if(lastOpen !== null) {
if(lastOpen === aboutLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-about').slideToggle('slow');
lastOpen = aboutLink;
}
);
$('.contact').click(function() {
if(lastOpen !== null) {
if(lastOpen === contactLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-contact').slideToggle('slow');
lastOpen = contactLink;
}
);
I am now trying to create the same result but with a single function instead of one for each link. This is what I came up with....
function navLink(contentClass, linkClass, linkId) {
this.contentClass = contentClass;
this.linkClass = linkClass;
this.linkId = linkId;
}
var navs = [];
navs[0] = new navLink(".content-home", "nav", "home");
navs[1] = new navLink(".content-about", "nav", "about");
navs[2] = new navLink(".content-contact", "nav", "contact");
var lastOpen = null;
$('.nav').click(function(event) {
//loop through link objects
var i;
for (i = 0; i < (navsLength + 1); i++) {
//find link object that matches link clicked
if (event.target.id === navs[i].linkId) {
//if there is a window opened, close it
if (lastOpen !== null) {
//unless it is the link that was clicked
if (lastOpen === navs[i]) {
return;
} else {
//close it
$(lastOpen.contentClass).slideToggle('fast');
}
}
//open the content that correlates to the link clicked
$(navs[i].contentClass).slideToggle('slow');
navs[i] = lastOpen;
}
}
});
JSFiddle - Doesn't Work
No errors so I assume that I am just doing this completely wrong. I've been working with Javascript for only about a week now. I've taken what I've learned about arrays and JQuery events and tried to apply them here. I assume I'm way off. Thoughts? Thanks
You just forgot to define navsLength:
var navsLength=navs.length;
Of course you could also replace it with a $().each loop as you're using jQuery.
[Update] Two other errors I corrected:
lastOpen=navs[i];
for(i=0; i < navsLength ; i++)
Demo: http://jsfiddle.net/jMzPJ/4/
Try:
var current, show = function(){
var id = this.id,
doShow = function() {
current = id;
$(".content-" + id).slideToggle('slow');
},
toHide = current && ".content-" + current;
if(current === id){ //Same link.
return;
}
toHide ? $(toHide).slideToggle('fast', doShow): doShow();;
};
$("#nav").on("click", ".nav", show);
http://jsfiddle.net/tarabyte/jMzPJ/5/