how to limit the click event in jquery loop? - javascript

I would like to limit click event loop in jquery. I have categories list which will have in the following format and also after 5 click in the loop i have to disable click event.
<div class="col-md-2 col-sm-4 col-xs-6 home_s">
<a class="get_category" id="36" href="javascript:void(0)">
<img class="img-responsive img-center" src="">
<span>xxxxx</span>
</a>
<input type="hidden" value="36" id="categories36" name="categories[]">
</div>
$(document).ready(function() {
$(".get_category").on('click', function() {
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
})
});

You can use off() to unbind event handler
$(document).ready(function() {
// variable for counting clicks
var i = 1;
var fun = function() {
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
// checking and increment click count
if (i++ == 5)
// unbinding click handler from element
$(".get_category").off('click', fun);
};
$(".get_category").on('click', fun);
});
Example :
$(document).ready(function() {
var i = 1;
var fun = function() {
alert('clicked'+i);
if (i++ == 5)
$(".get_category").off('click', fun);
};
$(".get_category").on('click', fun);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="get_category">click</button>

If you have multiple .get_category in your html the solution from Pranav C Balan won't work.
$(document).ready(function() {
function clickFunc() {
var click_count = $(this).data('click-count') || 0;
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
if (++click_count >= 5)
$(this).off('click', clickFunc);
$(this).data('click-count', click_count);
});
$(".get_category").on('click', clickFunc);
});
This way you store the click count on the data-click-count attribute of each .get_category

Related

Editing HTML table row data

Hello Folks..,
I am getting error while updating text field values. When I update one text field, the remaining are all updated automatically with same value.
Here is the link contains my source code:
http://jsfiddle.net/jFycy/284/
My requirement is to update that particular field only.
$(function () {
$(".inner, .inner2").dblclick(function (e) {
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
});
});
function updateVal(currentEle, value) {
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val().trim());
}
});
$(document).click(function () {
$(currentEle).html($(".thVal").val().trim());
});
}
You can do something like this
$(function() {
$(".inner, .inner2").dblclick(function(e) {
// check text input element contains inside
if (!$('.thVal', this).length)
// if not then update with the input element
$(this).html(function(i, v) {
return '<input class="thVal" type="text" value="' + v + '" />'
});
}).on({
// bind keyup event
'keyup': function(event) {
// on enter key update the content
if (event.keyCode == 13) {
$(this).parent().html($(this).val().trim());
}
},
'blur': function() {
// if focus out the element update the content with iput value
$(this).parent().html($(this).val().trim());
}
}, '.thVal');
});
.inner {
background: red;
}
.inner2 {
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inner">1</div>
<div class="inner2">1</div>
<div class="inner">1</div>
Or much more simpler method with a contenteditable attribute.
.inner {
background: red;
}
.inner2 {
background: grey;
}
<div contenteditable class="inner">1</div>
<div contenteditable class="inner2">1</div>
<div contenteditable class="inner">1</div>
Thing is, you using myltiple inputs and attaching event to every one of it.
Instead, I suggest you to create one input and use exactly this particular input.
function updateVal(currentEle, value) {
var $thval = $('<input class="thVal" type="text" value="' + value + '" />');
$(currentEle).empty().append($thval);
$thval.focus().keyup(function(event) {
if (event.keyCode == 13) {
$(this).blur();
}
}).blur(function(){
$(currentEle).html($(".thVal").val().trim());
$thval.remove();
});
}
http://jsfiddle.net/jFycy/290/
When multiple html element like (OL li) it duplicate value in other controls too. For this I have made this changes, and its working.
$(".updatefield").dblclick(function (e) {
**var len = $('.thVal').length;
if (len > 0) {
$(".thval").remove();
return;**
}
e.stopPropagation(); //<-------stop the bubbling of the event here
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
});
function updateVal(currentEle, value) {
var wid = currentEle.width() + 30;
var hei = currentEle.height()+ 10;
//$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
$(currentEle).html('<textarea class="thVal">' + value + '</textarea>');
$(".thVal").css("width", wid);
$(".thVal").css("height", hei);
$(".thVal").css("background", "lightyellow");
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
if ($(".thVal").val() == "")
$(".thVal").val("EMPTY");
$(currentEle).html($(".thVal").val().trim());
}
});
$(document).click(function () { // you can use $('html')
**var e = jQuery.Event("keyup");
e.which = 13; // Enter
e.keyCode = 13; // Enter
$('.thVal').trigger(e);**
});

Jquery tab is not working

I have one problem with click function. I have created this demo from jsfiddle.net.
In this demo you can see there are smile buttons. When you click those buttons then a tab will be opening on that time. If you click the red button from tab area then the tab is not working there are something went wrong.
Anyone can help me here what is the problem and what is the solution?
The tab is normalize like this working demo
var response = '<div class="icon_b">
<div class="clickficon"></div>
<div class="emicon-menu MaterialTabs">
<ul>
<li class="tab active"> TAB1</li>
<li class="tab"> TAB2</li>
<li class="tab"> TAB3<span></span></li>
</ul>
<div class="panels">
<div id="starks-panel1" class="panel pactive"> a </div>
<div id="lannisters-panel1" class="panel"> b </div>
<div id="targaryens-panel1" class="panel"> c </div>
</div>
</div>
</div>';
$(document).ready(function () {
function showProfileTooltip(e, id) {
//send id & get info from get_profile.php
$.ajax({
url: '/echo/html/',
data: {
html: response,
delay: 0
},
method: 'post',
success: function (returnHtml) {
e.find('.user-container').html(returnHtml).promise().done(function () {
$('.emoticon').addClass('eactive');
});
}
});
}
$('body').on('click', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
});
$(this).on( "click", function() {
$(this).find('.user-container').html("");
});
var componentHandler = function() {
'use strict';
var registeredComponents_ = [];
var createdComponents_ = [];
function findRegisteredClass_(name, opt_replace) {
for (var i = 0; i < registeredComponents_.length; i++) {
if (registeredComponents_[i].className === name) {
if (opt_replace !== undefined) {
registeredComponents_[i] = opt_replace;
}
return registeredComponents_[i];
}
}
return false;
}
function upgradeDomInternal(jsClass, cssClass) {
if (cssClass === undefined) {
var registeredClass = findRegisteredClass_(jsClass);
if (registeredClass) {
cssClass = registeredClass.cssClass;
}
}
var elements = document.querySelectorAll('.' + cssClass);
for (var n = 0; n < elements.length; n++) {
upgradeElementInternal(elements[n], jsClass);
}
}
function upgradeElementInternal(element, jsClass) {
if (element.getAttribute('data-upgraded') === null) {
element.setAttribute('data-upgraded', '');
var registeredClass = findRegisteredClass_(jsClass);
if (registeredClass) {
createdComponents_.push(new registeredClass.classConstructor(element));
} else {
createdComponents_.push(new window[jsClass](element));
}
}
}
function registerInternal(config) {
var newConfig = {
'classConstructor': config.constructor,
'className': config.classAsString,
'cssClass': config.cssClass
};
var found = findRegisteredClass_(config.classAsString, newConfig);
if (!found) {
registeredComponents_.push(newConfig);
}
upgradeDomInternal(config.classAsString);
}
return {
upgradeDom: upgradeDomInternal,
upgradeElement: upgradeElementInternal,
register: registerInternal
};
}();
function MaterialTabs(element) {
'use strict';
this.element_ = element;
this.init();
}
MaterialTabs.prototype.Constant_ = {
MEANING_OF_LIFE: '42',
SPECIAL_WORD: 'HTML5',
ACTIVE_CLASS: 'pactive'
};
MaterialTabs.prototype.CssClasses_ = {
SHOW: 'materialShow',
HIDE: 'materialHidden'
};
MaterialTabs.prototype.initTabs_ = function(e) {
'use strict';
this.tabs_ = this.element_.querySelectorAll('.tab');
this.panels_ = this.element_.querySelectorAll('.panel');
for (var i=0; i < this.tabs_.length; i++) {
new MaterialTab(this.tabs_[i], this);
}
};
MaterialTabs.prototype.resetTabState_ = function() {
for (var k=0; k < this.tabs_.length; k++) {
this.tabs_[k].classList.remove('pactive');
}
};
MaterialTabs.prototype.resetPanelState_ = function() {
for (var j=0; j < this.panels_.length; j++) {
this.panels_[j].classList.remove('pactive');
}
};
function MaterialTab (tab, ctx) {
if (tab) {
var link = tab.querySelector('a');
link.addEventListener('click', function(e){
e.preventDefault();
var href = link.href.split('#')[1];
var panel = document.querySelector('#' + href);
ctx.resetTabState_();
ctx.resetPanelState_();
tab.classList.add('pactive');
panel.classList.add('pactive');
});
}
};
MaterialTabs.prototype.init = function() {
if (this.element_) {
this.initTabs_();
}
}
window.addEventListener('load', function() {
componentHandler.register({
constructor: MaterialTabs,
classAsString: 'MaterialTabs',
cssClass: 'MaterialTabs'
});
});
});
There is updated and working version.
What we have to do, is to move the target on the same level as the icon is (almost like tab and content). Instead of this:
<div class="emoticon">
<div class="emoticon_click" data-id="1">
<img src="http://megaicons.net/static/img/icons_sizes/8/178/512/emoticons-wink-icon.png" width="30px" height="30px">
<div class="user-container" data-upgraded></div>
</div>
</div>
We need this
<div class="emoticon">
<div class="emoticon_click" data-id="1">
<img src="http://megaicons.net/static/img/icons_sizes/8/178/512/emoticons-wink-icon.png" width="30px" height="30px">
// not a child
<!--<div class="user-container" data-upgraded></div>-->
</div>
// but sibling
<div class="user-container" data-upgraded></div>
</div>
And if this is new HTML configuration, we can change the handlers
to target click on div "emoticon_click"
change the content of the sibling (not child) div "user-container"
The old code to be replaced
$('body').on('click', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
});
$(this).on( "click", function() {
$(this).find('.user-container').html("");
});
will now be replaced with this:
//$('body').on('click', '.emoticon', function(e) {
$('body').on('click', '.emoticon_click', function(e) {
// clear all user container at the begining of this click event
$('body').find('.user-container').html("");
// find id
var id = $(this).attr('data-id');
// find the parent, which also contains sibling
// user-container
var parent = $(this).parent()
// let the target be initiated
showProfileTooltip($(parent), id);
});
$(this).on( "click", function() {
//$(this).find('.user-container').html("");
});
Check it in action here
NOTE: the really interesting note was in this Answer by pinturic
If we want to extend the first and complete answer with a feature:
close all tabs if clicked outside of the area of tabs or icons
we just have to
add some event e.g. to body
and do check if the click was not on ".emoticon" class elements
There is a working example, containing this hook:
$('body').on( "click", function(e) {
// if clicked in the EMOTICON world...
var isParentEmotion = $(e.toElement).parents(".emoticon").length > 0 ;
if(isParentEmotion){
return; // get out
}
// else hide them
$('body').find('.user-container').html("");
});
I have been debugging your code and this is the result:
you are adding the "tab" under ; any time you click within that div this code is intercepting it:
$('body').on('click', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
});
and thus the "tab" are built again from scratch.

Updating interval dynamically - jQuery or Javascript

I have two "stopwatches" in my code (and I may be adding more). This is the code I currently use below - and it works fine. But I'd really like to put the bulk of that code into a function so I'm not repeating the same code over and over.
When I tried doing it though, I could get it working - I think it was because I was passing stopwatchTimerId and stopwatch2TimerId into the function and it may have been passing by reference?
How can I reduce the amount of code repetition here?
var stopwatchTimerId = 0;
var stopwatch2TimerId = 0;
$('#stopwatch').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
$(this).addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch-seconds').val()) || 0;
$('#stopwatch-seconds').val(currentValue + 1).change();
}, 1000);
}
});
$('#stopwatch2').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatch2TimerId);
}
else {
$(this).addClass('active');
stopwatch2TimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch2-seconds').val()) || 0;
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
});
As you can see, it's basically the same code in each except for stopwatchTimerId and $('#stopwatch-seconds') (and the same vars with 2 on it for the other one).
This won't pollute global scope and also you don't need to do any if-else statements. Just add data-selector to your new elements :)
<input id="stopwatch" type="text" data-selector="#stopwatch-seconds"/>
<input id="stopwatch2" type"text" data-selector="#stopwatch2-seconds"/>
$('#stopwatch stopwatch2').click(function () {
var $element = $(this),
interval = $element.data('interval');
selector = $element.data('selector');;
if ($element.hasClass('active')) {
$element.removeClass('active');
if (interval) {
clearInterval(interval);
}
}
else {
$element.addClass('active');
$element.data('interval', setInterval(function () {
var currentValue = parseInt($(selector).val()) || 0;
$(selector).val(currentValue + 1).change();
}, 1000));
}
});
function stopwatch(id){
$('#' + id).click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(window[id]);
}
else {
$(this).addClass('active');
window[id] = setInterval(function () {
var currentValue = parseInt($('#' + id + '-seconds').val()) || 0;
$('#' + id + '-seconds').val(currentValue + 1).change();
}, 1000);
}
});
}
$(function(){
stopwatch("stopwatch");
stopwatch("stopwatch2");
});
You could do something like this (code is not very nice, you can improve it):
var stopwatchTimerId;
$('#stopwatch').click(function () {
doStopWatch(1);
});
$('#stopwatch2').click(function () {
doStopWatch(2);
});
var doStopWatch = function(option){
var stopWatch = option===1?$('#stopwatch'):$('#stopwatch2');
if (stopWatch.hasClass('active')) {
stopWatch.removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
stopWatch.addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = option===1?(parseInt($('#stopwatch-seconds').val()) || 0):(parseInt($('#stopwatch2-seconds').val()) || 0);
if(option===1)
$('#stopwatch-seconds').val(currentValue + 1).change();
else
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
}
Try
var arr = $.map($("div[id^=stopwatch]"), function(el, index) {
el.onclick = watch;
return 0
});
function watch(e) {
var id = this.id;
var n = Number(id.split(/-/)[1]);
if ($(this).hasClass("active")) {
$(this).removeClass("active");
clearInterval(arr[n]);
} else {
$(this).addClass("active");
arr[n] = setInterval(function() {
var currentValue = parseInt($("#" + id + "-seconds").val()) || 0;
$("#" + id + "-seconds").val(currentValue + 1).change();
}, 1000);
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="stopwatch-0">stopwatch1</div>
<input type="text" id="stopwatch-0-seconds" />
<div id="stopwatch-1">stopwatch2</div>
<input type="text" id="stopwatch-1-seconds" />

Using jQuery with meteor giving errors

Omitting the keydown input : function(event) { and } gives me an error along the lines of
"While building the application:
client/client.js:33:11: Unexpected token ("
which is basically the starting. I'm wondering why I need the javascript function right at the start. To not get the error. This is an issue especially because I don't want the click function to run every time the key is pressed. In any case it would be great to either figure out how I can just use jQuery instead of javascript here or change the keydown input.
Template.create_poll.events = {
'keydown input' : function(event) {
$("input").keypress(function() {
var active_element = $(this).parent().attr("id");
var last_child = $('ul li:last').attr("id");
var option_number_index = last_child.lastIndexOf("-");
var option_number = last_child.substring(option_number_index+1);
option_number = option_number/1;
//console.log(option_number);
//console.log(last_child);
if (last_child == active_element) {
console.log(active_element);
option_number += 1;
console.log(option_number);
$('ul').append('<li id="poll-choice-' + option_number + '"><input name="choice" type="text" placeholder="Option ' + option_number + '">');
}
});
$("#poll_create").click(function() {
console.log("Button works");
var choices = new Array();
var counter = 0;
$("ul li input").each(function() {
choices[counter] = $(this).val();
counter++;
});
console.log(choices[1]);
console.log(choices[5]);
});
}
}
Template.create_poll.events expects an eventMap which is:
An event map is an object where the properties specify a set of events to handle, and the values are the handlers for those events. The property can be in one of several forms:
Hence, you need to pass in the 'keydown input' : function (event, templ) { ... } to make it a valid Javascript object.
In this case, you should follow #Cuberto's advice and implement the events using Meteor's event map:
Template.create_poll.events = {
'press input' : function(event) {
var active_element = $(this).parent().attr("id");
var last_child = $('ul li:last').attr("id");
var option_number_index = last_child.lastIndexOf("-");
var option_number = last_child.substring(option_number_index+1);
option_number = option_number/1;
//console.log(option_number);
//console.log(last_child);
if (last_child == active_element) {
console.log(active_element);
option_number += 1;
console.log(option_number);
$('ul').append('<li id="poll-choice-' + option_number + '"><input name="choice" type="text" placeholder="Option ' + option_number + '">');
}
},
'click #poll_create' : function (event) {
console.log("Button works");
var choices = new Array();
var counter = 0;
$("ul li input").each(function() {
choices[counter] = $(this).val();
counter++;
});
console.log(choices[1]);
console.log(choices[5]);
}
}
However, if you want to use certain jQuery specific events, then you can attach them in the rendered function:
Template.create_poll.rendered = function () {
$("input").keypress(function() {
var active_element = $(this).parent().attr("id");
var last_child = $('ul li:last').attr("id");
var option_number_index = last_child.lastIndexOf("-");
var option_number = last_child.substring(option_number_index+1);
option_number = option_number/1;
//console.log(option_number);
//console.log(last_child);
if (last_child == active_element) {
console.log(active_element);
option_number += 1;
console.log(option_number);
$('ul').append('<li id="poll-choice-' + option_number + '"><input name="choice" type="text" placeholder="Option ' + option_number + '">');
}
});
$("#poll_create").click(function() {
console.log("Button works");
var choices = new Array();
var counter = 0;
$("ul li input").each(function() {
choices[counter] = $(this).val();
counter++;
});
console.log(choices[1]);
console.log(choices[5]);
});
};

jQuery - Click function doesn't fire

I'm having problems with firing of a function whenever my ID is clicked. Currently, this is how my code looks:
$(document).ready(function () {
if (self != top) {
top.location.replace(location.href);
}
$(document).mousedown(function (e) {
if (e.button == 2) {
console.log('mousdown');
$(window).blur();
}
});
$(document).mouseup(function (e) {
if (e.button == 2) {
console.log('mousup');
$(window).blur();
}
});
var $iframe_height = $(window).innerHeight() - 90;
$('iframe').attr('height', $iframe_height + 'px');
$(window).resize(function () {
var $iframe_height = $(window).innerHeight() - 90;
$('iframe').attr('height', $iframe_height + 'px');
});
$('.message').html('<div class="alert alert-warning">Waiting for advertisement to load...</div>');
$('.close').on('click', function () {
window.open('', '_self', '');
window.close();
});
var $seconds = 5;
var $window_width = $(window).innerWidth();
var $width_per_second = $window_width / $seconds;
var $timer = null,
$current_second = 0;
setTimeout(function () {
if ((!$('body').hasClass('done')) && (!$('body').hasClass('blocked')) && (!$('body').hasClass('ready'))) {
$('body').addClass('ready');
$('.message').html('<div class="alert alert-info">Click <b id="start" style="cursor:pointer;text-decoration:underline;">here</b> to start viewing this advertisement.</div>');
}
}, 3000);
document.getElementById("website").onload = function () {
if ((!$('body').hasClass('done')) && (!$('body').hasClass('blocked')) && (!$('body').hasClass('ready'))) {
$('body').addClass('ready');
$('.message').html('<div class="alert alert-info">Click <b id="start" style="cursor:pointer;text-decoration:underline;">here</b> to start viewing this advertisement.</div>');
}
};
$("#start").click(function () {
$('#website').focus();
$('.message').html('<div class="alert alert-info"><b id="seconds">' + parseFloat($seconds - $current_second) + '</b> seconds remaining (do not leave this page).</div>');
if ($timer !== null) return;
$timer = setInterval(function () {
if ($current_second == $seconds) {
clearInterval($timer);
$('.message').html('<div class="alert alert-success">Checking if you won, please wait…</div>');
var $id = 10977;
var $reffbux_fp = new Fingerprint();
var $reffbux_fp = $reffbux_fp.get();
$.ajax({
url: 'http://reffbux.com/account/register_roulette',
type: 'post',
data: {
id: $id,
fp: $reffbux_fp
},
success: function (result, status) {
$('html, body').animate({
scrollTop: 0
}, 500);
$('body').addClass('done');
$('.melding').fadeOut(0).fadeIn(500);
$('.message').html(result);
$('.counter_bar').addClass('done');
}
});
return false;
} else {
var $counter_bar_width = $('.counter_bar').innerWidth();
$('.counter_bar').css('width', parseFloat($counter_bar_width + $width_per_second).toFixed(2));
$current_second++;
$("#seconds").text(parseFloat($seconds - $current_second));
}
}, 1000);
});
$('body').mouseleave(function () {
if ((!$(this).hasClass('done')) && (!$(this).hasClass('blocked')) && ($(this).hasClass('ready'))) {
$('.message').html('<div class="alert alert-error">You navigated away from the advertisement. Click <b id="start" style="cursor:pointer;text-decoration:underline;">here</b> to resume.</div>');
clearInterval($timer);
$timer = null
}
});
});
A text with id="start" will be generated when the iframes content is loaded. The problem is, whenever I click on the id="start" nothing happens. Nothing. The console log doesn't report any error before I click nor does it report any error after I've clicked.
I can't seem to find what the problem is.
You have to use the jquery on to bind events to dynamically created elements.
$('.message').on('click', '#start', function(){
Where .message is the elelment your #start element is in.

Categories