jquery click does not work - javascript

Anyone have an idea why my jQuery click won't work?
It's attached to a hyperlink.
jQuery(function ($) {
$(".delete").click(function(e) {
alert("Hello");
});
var socket = io.connect();
var $messageForm = $('#sendmessage');
var $messageTitle = $('#title');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.click(function (e) {
if ($.trim($("#title").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
}
if ($.trim($("#message").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
} else {
e.preventDefault();
socket.emit('send message',
'<b>' + $messageTitle.val() + '</b>' + ' - '
+ $messageBox.val() + ' ' + '[' +
'<a class="delete" href="#">Delete</a>' + ']');
$messageTitle.val('');
$messageBox.val('');
}
});
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
});

Since the delete links are dynamically generated, you need to use event delegation:
$('#chat').on('click', '.delete', function(e) {
alert("Hello");
});

Hello try to modify your jquery initialization like this:
(function($){ }(jQuery)
If your script still doesn't fire the click event, check if $messageForm exists, using console.log($messageForm). You can modify var $messageForm in var messageForm from what I seen that variable does not need a scope so wide. I hope this could help you

Related

Javascript Toggle HTML

I am creating an app that allows the user to check the local weather and temperature in celsius or fahrenheit. However, I am having a problem when toggling between the two unit types when the temperature is clicked on. This is the link to my demo.
And here is my Javascript code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$.getJSON("https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&units=imperial&appid=a62849f462c6573114f32a691f5d3c3f", function(json) {
var all = JSON.stringify(json);
var weather = JSON.stringify(json.weather[0]["description"]);
weather = weather.slice(1, -1);
var tempFahrenheit = JSON.stringify(json.main.temp);
var tempCelsius = JSON.stringify(json.main.temp * 2);
$("#weather").html(weather);
$("#temp").html(Math.floor(tempFahrenheit) + " °<span id='units'>F</span>");
$("#units").on('click', function() {
if ($(this).text() == "F") {
$("#temp").html(Math.floor(tempCelsius) + " °<span id='units'>C</span>");
} else {
$("#temp").html(Math.floor(tempFahrenheit) + " °<span id='units'>F</span>");
}
});
});
});
}
When you replace the html contents of the #temp div, you lose your event handler on the units div as well. Use event delegation instead. Assign the event on the body tag, but listen for events on the #units div.
Updated code:
$("body").on('click', '#units', function() {
if ($(this).text() == "F") {
$("#temp").html(Math.floor(tempCelsius) + " °<span id='units'>C</span>");
} else {
$("#temp").html(Math.floor(tempFahrenheit) + " °<span id='units'>F</span>");
}
});
Working fork of your Codepen: https://codepen.io/anon/pen/AXzYzR?editors=0010

get message without re open div

Im working in a chat system very simple. But i have a problem. I can only get the other user messages if i close and re open the chat conversation div, then the message appears.
How can I solve this? The problem should be in this piece of code. As I am not very comfortable with ajax I ask for your help.
JS:
$(document).ready(function(){
var snd = new Audio("images/new_msg.wav");
var open=Array();
$("#jd-chat .jd-online_user").click(function(){
var user_name = $.trim($(this).text());
var id = $.trim($(this).attr("id"));
if($.inArray(id,open) !== -1 )
return
open.push(id);
$("#jd-chat").prepend('<div class="jd-user">\
<div class="jd-header" id="' + id + '">' + user_name + '<span class="close-this"> X </span></div>\
<div class="jd-body"></div>\
<div class="jd-footer"><input id="textareabox" placeholder="escrever..."></div>\
</div>');
$.ajax({
url:'chat.class.php',
type:'POST',
data:'get_all_msg=true&user=' + id ,
success:function(data){
$("#jd-chat").find(".jd-user:first .jd-body").append("<span style='display:block' class='me'> " + data + "</span>");
}
});
});
$("#jd-chat").delegate(".close-this","click",function(){
removeItem = $(this).parents(".jd-header").attr("id");
$(this).parents(".jd-user").remove();
open = $.grep(open, function(value) {
return value != removeItem;
});
});
$("#jd-chat").delegate(".jd-header","click",function(){
var box=$(this).parents(".jd-user,.jd-online");
$(box).find(".jd-body,.jd-footer").slideToggle();
});
$("#search_chat").keyup(function(){
var val = $.trim($(this).val());
$(".jd-online .jd-body").find("span").each(function(){
if ($(this).text().search(new RegExp(val, "i")) < 0 )
{
$(this).fadeOut();
}
else
{
$(this).show();
}
});
});
$("#jd-chat").delegate(".jd-user input","keyup",function(e){
if(e.keyCode == 13 )
{
var $cont = $('.jd-body');
var box=$(this).parents(".jd-user");
var msg=$(box).find("input").val();
var to = $.trim($(box).find(".jd-header").attr("id"));
$.ajax({
url:'chat.class.php',
type:'POST',
data:'send=true&to=' + to + '&msg=' + msg,
success:function(data){
$('#textareabox').val('');
$(box).find(".jd-body").append("<span style='display:block' class='me'> " + msg + "</span>");
$cont[0].scrollTop = $cont[0].scrollHeight;
$cont.append('<span>' + $(this).val() + '</span>');
$cont[0].scrollTop = $cont[0].scrollHeight;
$(this).val('');
}
});
}
});
function message_cycle()
{
$.ajax({
url:'chat.class.php',
type:'POST',
data:'unread=true',
dataType:'JSON',
success:function(data){
$.each(data , function( index, obj ) {
var user = index;
var box = $("#jd-chat").find("div#2").parents(".jd-user");
$(".jd-online").find(".light").hide();
$.each(obj, function( key, value ) {
if($.inArray(user,open) !== -1 )
$(box).find(".jd-body").append("<span style='display:block' class='other'> " + value + "</span>");
else
snd.play();
$(".jd-online").find("span#" + user + " .light").show();
});
});
}
});
}
setInterval(message_cycle,1000);
});
How messages are displayed when you first open the chat conv div ?
I'm assuming message_cycle() is supposed to display new messages in your div every second, i suppose your problem is here...
I'm not really confortable with this :
var box = $("#jd-chat").find("div#2").parents(".jd-user");
A div can't have an id starting with a number, you need <div id="chat2"> instead of <div id="2">.
After your line add a console.log('Box found : '+box.length) ; just to make sure your box is correctly found in message_cycle.

Out of order execution - no Ajax involved

I'm experiencing some out-of-order execution in javascript, and it's not related to any ajax calls or such. The main bulk of code is a possibly slow DOM manipulation, followed by a method call. In every single case, the function call is being fired before the DOM manipulation finishes.
Here is my code:
$(this).parents('dd').siblings('dd').each(function(){
var filter_name = $(this).attr('data-filter-type');
if ($(this).hasClass('selected')) {
$(this).removeClass('selected', function(){
if ($(this).hasClass('date')) {
$('form[name="filter-form"] input[name="from"]').remove();
$('form[name="filter-form"] input[name="to"]').remove();
} else {
$('form[name="filter-form"] input[name="' + filter_name + '"]').remove();
}
console.log('removed');
});
}
});
var filter_type = $(this).parents('dd').attr('data-filter-type');
var filter_input = 'form[name="filter-form"] input[name="' + filter_type + '"]';
if ($(filter_input).length > 0) {
$(filter_input).val(filter_value);
} else {
$('form[name="filter-form"]').append('<input type="hidden" name="' + filter_type + '" value="true">');
}
doStuff($(this));
In my console, I am seeing the result of doStuff before I am seeing the debug.
Anybody have any ideas how to make the function call wait?
There is an overload of .removeClass that takes a function, but it's not a callback function (that operation is completed synchronously). I'd recommend removing the function argument to removeClass and placing the code immediately after that call:
$(this).parents('dd').siblings('dd').each(function(){
var filter_name = $(this).attr('data-filter-type');
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
if ($(this).hasClass('date')) {
$('form[name="filter-form"] input[name="from"]').remove();
$('form[name="filter-form"] input[name="to"]').remove();
} else {
$('form[name="filter-form"] input[name="' + filter_name + '"]').remove();
}
console.log('removed');
}
});
var filter_type = $(this).parents('dd').attr('data-filter-type');
var filter_input = 'form[name="filter-form"] input[name="' + filter_type + '"]';
if ($(filter_input).length > 0) {
$(filter_input).val(filter_value);
} else {
$('form[name="filter-form"]').append('<input type="hidden" name="' + filter_type + '" value="true">');
}
doStuff($(this));
I would wrap all your DOM manipulation into a function accepting callback as a parameter:
var manipulateDOM = function(callback){
...
if(typeof callback === "function")callback();
}
and call it like this:
manipulateDOM(function(){
doStuff(param);//I am not sure about the context so you need to figure out the value of param
})

Focus and blur events triggered on wrong element

I'm trying to set a default value for several inputs at once, removing that value on focus and setting it again on blur if the input is empty. To achieve that, using jQuery, I've got this code:
var settings = {
value: '',
focusColor: 'black',
blurColor: '#CCC',
value : 'test'
};
$.each($('input'), function(index, el) {
$(el).on('blur', function(ev) {
$el = $(this);
console.log('blur ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == '')
$el.attr('value', settings.value).css('color', settings.blurColor);
}).on('focus', function(ev) {
console.log('focus ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == settings.value)
$(this).attr('value', '').css('color', settings.focusColor);
});
$(el).trigger('blur');
});
Having this HTML:
<input id="text" type="text" />
<input id="email" type="email" />
The problem is that, if I focus on the first input and right after on the second one, the events triggered are: focus on first input, blur on first input and focus on first input again. So if I type something in the first one, then focus on the second and in the first one again, it won't remove the sample text and will remove what I typed in.
You can see the (not) working example here. Opening the JavaScript console you'll see clearly the wrong behavior.
​
You forgot the set $el inside the focus event.
$.each($('input'), function(index, el) {
$(el).on('blur', function(ev) {
$el = $(this);
console.log('blur ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == '')
$el.attr('value', settings.value).css('color', settings.blurColor);
}).on('focus', function(ev) {
$el = $(this); // <-- should update $el
console.log('focus ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == settings.value)
$(this).attr('value', '').css('color', settings.focusColor);
});
$(el).trigger('blur');
});
do you mean something like this:
$('input').on('blur', function(ev) {
$el = $(this);
console.log('blur ' + $el.va() + ' ' + $el.attr('id'));
if ($el.val() == '')
$el.attr('value', settings.value).css('color', settings.blurColor);
})
$('input').on('focus', function(ev) {
$el = $(this);
console.log('focus ' + $el.val() + ' ' + $el.attr('id'));
if ($el.val() == settings.value) {
$(this).val("");
$(this).css('color', settings.focusColor);
}
});
DEMO: http://jsfiddle.net/fnBeZ/4/

How to get the URL parameters after redirecting using javascript?

After replacign the location with new parameters, the page after loaded doesn't get the paramaters value, despite there are values in the parameters
the used code is :
function getURLParameter(name) {
return
decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
}
$(document).ready(function () {
$(".sub").slideUp();
var div = getURLParameter("div");
var ddl = getURLParameter("ddl");
alert(div);
// alert("ManageTrainingNeeds.aspx?div=" + div + "&ddl=" + ddl);
// $("#" + div).slideDown();
// $("#ddlObjectiveGroup").val("'" + ddl + "'");
});
$(".btnAddSub").live("click", function () {
var diva = $(this).parent().parent().parent().parent().parent().parent().attr("id");
var ddl = $("#ddlObjectiveGroup option:selected").val();
window.location.replace("ManageTrainingNeeds.aspx?div=" + diva + "&ddl=" + ddl);
});
this alert(div); return undefined.. despite the div vairable in click event has a value
Try encoding the parameters and also canceling the default action in the click event:
function getURLParameter(name) {
return decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
}
$(document).ready(function () {
var div = getURLParameter('div');
var ddl = getURLParameter('ddl');
alert(div + ' ' + ddl);
});
$('.btnAddSub').live('click', function () {
var diva = encodeURIComponent($(this).parent().parent().parent().parent().parent().parent().attr('id'));
var ddl = encodeURIComponent($('#ddlObjectiveGroup').val());
window.location.replace('/ManageTrainingNeeds.aspx?div=' + diva + '&ddl=' + ddl);
return false;
});
Instead of fiddling with the URLs yourself, you could use a library for the job - such as URI.js. (sorry for the self-promo)
$(document).ready(function () {
var search = URI().search(true);
alert(search.div + ' ' + search.ddl);
});
$('.btnAddSub').live('click', function (e) {
var uri = URI('/ManageTrainingNeeds.aspx');
uri.search({
diva: $(this).parent().parent().parent().parent().parent().parent().attr('id'),
ddl: $('#ddlObjectiveGroup').val()
});
window.location.href = uri.toString();
e.preventDefault();
});

Categories