This question already has answers here:
jQuery doesn't work after content is loaded via AJAX
(9 answers)
Closed 9 years ago.
here is my js function to load html
function getLeftCategories() {
var id = 3;
$.getJSON("/api/kategori/getKategoriByTedarikci/" + id, function (data) {
var obj = jQuery.parseJSON(data);
$.each(obj, function () {
if (this.UstKategoriId == null) {
var kTop =
'<li>' +
'<a>' + this.KategoriAdi + '<span>+</span></a>' +
'<ul id="ulAltKategori">' +
'</ul>' +
'</li>'
$("#ulKategoriler").append(kTop);
}
});
$.each(obj, function () {
if (this.UstKategoriId != null) {
var sTop =
'<li>' +
'<a>- ' + this.KategoriAdi + '</a>' +
'</li>'
$("#ulAltKategori").append(sTop);
}
});
});
}
this is my html side
<div class="box">
<div class="box-heading">Kategoriler</div>
<div class="box-content">
<div class="box-category">
<ul id="ulKategoriler">
</ul>
</div>
</div>
here is my script function to toggle
$(function () {
$('.box-category a > span').each(function () {
if (!$('+ ul', $(this).parent()).length) {
$(this).hide();
}
});
$('.box-category a > span').click(function (e) {
debugger;
e.preventDefault();
$('+ ul', $(this).parent()).slideToggle();
$(this).parent().toggleClass('active');
$(this).html($(this).parent().hasClass('active') ? "-" : "+");
return false;
});
$('.filter-active span').click();
});
if i add the html from javascript toggle function is not working am i missing something which one is load to page first time ?
If this is dynamically loaded html then you will need event delegation to handle this
$(document).on('click', ".box-category a > span", function () {
...
}
Just change your script:
$('.box-category a > span').click(function (e) {
debugger;
e.preventDefault();
...
}
to
$('.box-category').on('click', 'a > span', function (e) {
debugger;
e.preventDefault();
e.stopPropagation();
...
}
Related
I have this jquery slider from some author. I do have autoplay feature built in. But when I am using it in my website the jquery sliders are not changing on autoplay. Following is the code for that
According to the documentation to make the slide autoplay you need to put the below code into your main index HTML file. But even after adding this code the slides autoplay is not working. And no error is reported in the console.
I've put this code after the script tag which adds slider.js to the HTML.
code in index.html
<script>
$(function () {
$('#slider').rbtSlider({
height: '500px',
'dots': true,
'arrows': true,
'auto': 1
});
});
</script>
The slider html code
<div class="slider" id="slider">
<div class="slItems">
<div class="slItem">
<div class="slText">
<p>
some content
</p>
</div>
</div>
<div class="slItem">
<div class="slText">
<p>
some content
</p>
</div>
</div>
</div>
</div>
the slider.js code
jQuery.fn.rbtSlider = function(opt){
return this.each(function() {
var slider = $(this);
if (opt.height) slider.css('height', opt.height);
slider.find('.slItem').first().addClass('active');
if (opt.dots) {
var count = slider.find('.slItem').length;
slider.append(
$('<div/>', {
class: 'slDots',
html: $('<div/>', {
class: 'slDotsSingle active'
})
})
);
for (var i = 1; i < count; i++) {
slider.find('.slDotsSingle.active').clone().removeClass('active').appendTo($(this).find('.slDots'));
}
slider.find('.slDotsSingle').on('click', function(){
curIndex = $(this).parents('.slDots').find('.active').removeClass('active').index() + 1;
index = $(this).addClass('active').index() + 1;
if (index != curIndex) {
if (index > curIndex) nav('next', index);
else nav('prev', index);
}
});
}
if (opt.arrows) {
slider.append(
$('<div/>', {
class: 'ctrlPrev',
html: '‹'
}).on('click', function(){
nav('prev');
})
).append(
$('<div/>', {
class: 'ctrlNext',
html: '›'
}).on('click', function(){
nav('next');
})
);
}
if (opt.auto) {
var time = setInterval(function(){nav('next')}, opt.auto * 1000);
slider.on('mouseover', function() {
clearInterval(time);
}).on('mouseleave', function() {
time = setInterval(function(){nav('next')}, opt.auto * 1000);
});
}
function nav(side, index) {
if (index) {
nextItem = slider.find('.slItem').eq(index - 1);
} else {
if (side == 'prev') {
if (slider.find('.slItem.active').prev().length) nextItem = slider.find('.slItem.active').prev();
else nextItem = slider.find('.slItem').last();
} else {
if (slider.find('.slItem.active').next().length) nextItem = slider.find('.slItem.active').next();
else nextItem = slider.find('.slItem').first();
}
slider.find('.slDots > .active').removeClass('active').parent().find('.slDotsSingle').eq(nextItem.index()).addClass('active');
}
nextItem.addClass(side + 'Item').delay(50).queue(function(){
slider.find('.slItems > .active').addClass(side).delay(700).queue(function(){
$(this).removeClass(side +' active').dequeue();
});
$(this).addClass(side).delay(700).queue(function(){
$(this).removeClass(side + ' ' + side + 'Item').addClass('active').clearQueue();
});
$(this).dequeue();
});
}
});
};
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);**
});
So I have a MVC code that generates something like this
<div class="photoset">
<img />
<img />
</div>
<div class="photoset">
<img />
<img />
<img />
</div>
And I'm trying to make a jQuery to infinite scroll and as the user is scrolling, it generates more photosets.
I was somewhat successful in doing that but, after I generate more photosets with my infinite scroll, the newly added code won't work with my previous jQuery plugin to navigate between images.
Here is the jQuery code to navigate:
jQuery
$(document).ready(function () {
$('.photoset').each(function () {
$(this).data('counter', 0);
$items = $(this).find('img')
$(this).data('numItems', $items.length);
$(this).closest('.row').prev('.row').find('.nav-informer').text($(this).data('counter') + 1 + " de " + $(this).data('numItems'));
if (($items.eq(0).width() / $items.eq(0).height()) < 1) {
$(this).css({
width: "445",
height: "667",
margin: "auto"
});
}
});
var showCurrent = function (photoset) {
$items = photoset.find('img');
var counter = photoset.data('counter');
var numItems = $items.length;
var itemToShow = Math.abs(counter % numItems);
$items.fadeOut(1000);
$items.eq(itemToShow).fadeIn(1000);
};
/* ---------------------------------------------- /*
* Prev
/* ---------------------------------------------- */
$('.prev').on('click', function () {
var photoset = $(this).closest('.row').prev('.row').find('.photoset');
photoset.data('counter', photoset.data('counter') - 1);
if (photoset.data('counter') < 0)
photoset.data('counter', photoset.data('numItems') - 1);
photoset.closest('.row').prev('.row').find('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));
showCurrent(photoset);
});
/* ---------------------------------------------- /*
* Next
/* ---------------------------------------------- */
$('.next').on('click', function () {
var photoset = $(this).closest('.row').prev('.row').find('.photoset');
photoset.data('counter', photoset.data('counter') + 1);
if (photoset.data('counter') > photoset.data('numItems') - 1)
photoset.data('counter', 0);
photoset.closest('.row').prev('.row').find('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));
showCurrent(photoset);
});
});
And the Ajax function to call for more photosets, passing the page number:
Ajax
var page = 0,
inCallback = false,
hasReachedEndOfInfiniteScroll = false;
var ulScrollHandler = function () {
if (hasReachedEndOfInfiniteScroll == false &&
($(window).scrollTop() == $(document).height() - $(window).height())) {
loadMoreToInfiniteScrollUl(moreRowsUrl);
resizeNewElements();
}
}
function loadMoreToInfiniteScrollUl(loadMoreRowsUrl) {
if (page > -1 && !inCallback) {
inCallback = true;
page++;
$(".loading").show();
$.ajax({
type: 'GET',
url: loadMoreRowsUrl,
data: "pageNum=" + page,
success: function (data, textstatus) {
if (data != '') {
$(".infinite-scroll").append(data);
}
else {
page = -1;
}
inCallback = false;
$(".loading").hide();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
}
}
function showNoMoreRecords() {
hasReachedEndOfInfiniteScroll = true;
}
And this is the function that calls the infinite scroll:
$(function () {
$(".loading").hide();
});
var moreRowsUrl = '#Url.Action("index", "home")';
$(window).scroll(ulScrollHandler);
I did some research but couldn't stabilish a reason why my code doesn't work, tried some things but did not have success. If anyone could help me, would be great! Thanks in advance, and sorry for any mistake, I'm extremely new with jQuery and Ajax.
You can try with the event delegation for the click event on .prev and .next elements:
$(document).ready(function(){
$(document).on('click', '.prev', function(){.....});
$(document).on('click', '.next', function(){.....});
});
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
I want to move items between two Listboxes in ASP.Net using JQuery/Javascript and below is my code which is working perfectly.
function AddItems() {
var totalItemsSelected = 0;
var CurrentItems = 0;
var MessageLabel = document.getElementById('<%=lblITProgrammingMessage.ClientID%>');
var selectedOptions = jQuery('#<%=ListITProgramming.ClientID %> option:selected');
if (selectedOptions.length == 0) {
MessageLabel.innerHTML = "Please select skill(s) to add.";
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeOut(2000, function () { MessageLabel.innerHTML = ""; });
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeIn(500, function () { });
return false;
}
jQuery('select[name$=ListMyITProgramming] > option').each(function () { CurrentItems++; });
if (CurrentItems == 30) {
MessageLabel.innerHTML = "Maximum limit (30) is reached. You cannot add any more skills.";
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeOut(2000, function () { MessageLabel.innerHTML = ""; });
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeIn(500, function () { });
return false;
}
totalItemsSelected = CurrentItems + selectedOptions.length;
if (totalItemsSelected > 30) {
MessageLabel.innerHTML = "You can only select " + (30 - CurrentItems) + " item(s) more.";
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeOut(2000, function () { MessageLabel.innerHTML = ""; });
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeIn(500, function () { });
return false;
}
if (selectedOptions.length == 1) {
if (jQuery("#<%=ListMyITProgramming.ClientID %> option[value='" + selectedOptions.val() + "']").length > 0) {
}
else {
jQuery('#<%=ListMyITProgramming.ClientID %>').append(jQuery(selectedOptions).clone());
}
}
else if (selectedOptions.length > 1) { jQuery(selectedOptions).each(function () { if (jQuery("#<%=ListMyITProgramming.ClientID %> option[value='" + this.value + "']").length > 0) { } else { jQuery('#<%=ListMyITProgramming.ClientID %>').append(jQuery(this).clone()); } }); }
jQuery(selectedOptions).remove();
var hdn2 = "";
jQuery('select[name$=ListMyITProgramming] > option').each(function () { hdn2 += jQuery(this).attr('value') + ','; });
jQuery("#<%= listMyITProgrammingValues.ClientID %>").val(hdn2);
return false;
}
But this code is limited for only one set of ListBoxes as I have hard coded the ListBox names 'ListITProgramming' and 'ListMyITProgramming'.
Can anyone make this dynamic with two parameters in existing function?
Enclose the list control in an old-fashioned HTML tag with a known, hardcoded ID. Example:
<DIV id="List1Container">
<ASP:ListBox runat="server" id="list1"/>
</DIV>
In your Javascript, access the list control using the div's ID (List1Container) and jquery's ":first-child" selector. Ta da! You can now reference the list control without knowing its ID at all, so you don't have to do that messy code injection any more.
Bonus: Using this technique, you can now write fully static .js files, which means you can use minification and caching and greatly improve performance.