Kill twice called function and reload once onclick [duplicate] - javascript

I'm using JQuery lightSlider. It works pretty well (well, actually, I had to jig the code a little bit, but enough of that for now).
What I am trying to achieve is to dynamically replace the lightSlider content with ajax return data, and this I can do.
With each new data set, I call the lightSlider plugin again. This is the "success" or "done" section of my ajax function:
var lightsliderstring = "";
for(i=1;i<thumbsArray.length;i++){
lightsliderstring += "<li>\n";
if( $("#as_feature").val() ){
lightsliderstring += " <h3>" + $("#as_feature").val() + " photo " + i + "</h3>\n";
}
lightsliderstring += " <img src=\"/" + thumbsArray[i] + "\" />\n";
lightsliderstring += "</li>\n";
}
$("#lightSlider").html(lightsliderstring);
$('#lightSlider').lightSlider({
auto: true,
gallery: false,
item: 1,
loop: true,
slideMargin: 0,
thumbItem: 0
});
I call lightSlider again, with each new ajax call, because calling lightSlider only once doesn't seem to work. Maybe it's because the content is dynamically created after the DOM is loaded? Anyway, what I would like to do is clear the lightSlider function after each ajax call, because I think they are piling up on each other in the same div.
After one lightSlider call, it looks good:
But on my second ajax call, when lightSlider is instantiated again, it starts to "stack". Notice the doubled-arrows, vertically misaligned, and also the vertically doubling of the index dots below the picture:
What would cure this is some way to clear the first instance of lightSlider.

Assuming you are using a newer version of lightslider than 1.1.3 you should be able to .destroy() the existing instance as follows:
var slider = $('#lightslider').lightSlider();
slider.destroy();
For safety, you will need to check the slider is something before you call the destroy method though!

The $("#lightSlider").empty() or $("#lightSlider").html('') didn't work for some reason. The lightslider instances continued to pile up with every new form submission. I don't know why. Neither did the ("#lightSlider").lightslider().destroy() method seem to work, and that could be for some odd reason that I can't pinpoint, maybe something to do with the way I'm manipulating the DOM, I don't know.
What finally worked was to nest the <ul id="lightSlider">...</ul> block within a <div id="carousel-container">...</div> block. Then, with each new form submission, I deleted the entire #lightSlider block with a $("#carousel-container").html(''); Then I dynamically re-created the entire <ul id="lightSlider">...</ul> with the new, updated content. Here's the working code:
$("#carousel-container").html('');
var lightsliderstring = "<ul id=\"lightSlider\">";
for(i=1;i<thumbsArray.length;i++){
lightsliderstring += "<li>\n";
if( $("#as_feature").val() ){
lightsliderstring += " <h3>" + $("#as_feature").val() + " photo " + i + "</h3>\n";
}
lightsliderstring += " <img src=\"/" + thumbsArray[i] + "\" />\n";
lightsliderstring += "</li>\n";
}
lightsliderstring += "</ul>\n";
$("#carousel-container").html(lightsliderstring);
$('#lightSlider').lightSlider({
auto: true,
gallery: false,
item: 1,
loop: true,
slideMargin: 0,
thumbItem: 0
});

Related

change a variable in a nested function

i am trying to change a variable in a nested function, it's a lot of code so here is a simplified build up of the JS file
var time = 0;
$("button").click(function(){
time = time + 1
});
function thisIsTheTime(){
clockDesign()
// big bunch of variables and more code
}
function clockDesign(){
ProgressIndicator: {
name: "ProgressIndicator",
element: create_element_with_attributes("div", {
innerHTML:
"<div class='ProgressbarContainer' style='text-align: center;'>
+ time
+ </div>"
})
}
}
what i try to achieve is the following, update the time - each time a person clicks the button - in the second function ClockDesign() However this is rendered directly when the page loads. it keeps the 0.
You can try updating your click event with this -
$("button").click(function(){
time = time + 1
$(".ProgressbarContainer").text(time);
});

Initializing swiper sliders dynamically unexplainable behaviour

I have to create instances of swiper dynamically. These swipers have dynamically filled image contents. I have been fighting this the whole day with my lacking skills and cannot get this to work.
There are no javascript console errors, so I am assuming something is very fundamentally wrong but I don't know what it is.
Here is the code:
<!-- The sliders are initiated very standard way, i skipped showing them. These are my paginations where I cannot get the pagination to be rendered -->
<div class="secondary-0 swiper-pagination-clickable swiper-pagination-bullets"></div>
<div class="secondary-1 swiper-pagination-clickable swiper-pagination-bullets"></div>
<div class="secondary-2 swiper-pagination-clickable swiper-pagination-bullets"></div>
<script>
// I get lots of image data from php here
var imagearrays = <?php echo json_encode( $images_multiarray_js ); ?>;
// initialize variables for use in the loop.
var i;
var subNameArray = [];
var subSwiper = [];
// Loop through the imagearrays variable and initiate swipers.
for (i = 0; i < imagearrays.length; i++) {
subNameArray[i] = imagearrays[i].imagenames;
subSwiper = new Swiper('.subswiper-' + i, { // all my swiper-containers have extra class "subswiper-0" "subswiper-1" etc.
pagination: { // my main issue: I cannot get this pagination to render. WHY?
el: '.secondary-' + i, //my paginations have class like "secondary-0"
clickable: true,
renderBullet: function (index, className) {
return '<span class="' + className + '"><div class="pagination-ball"></div>' + subNameArray[index] + '</span>';
}
},
loop:true,
effect: 'fade',
clickable:true,
disableOnInteraction:false,
});
}
</script>
This is what my imagearrays variable looks like, just to show you that it's fine.
[
{"controllertype":false,"imagenames":["name1","name2"]},
{"controllertype":true,"imagenames":["name3","name4"]},
{"controllertype":false,"imagenames":["name5","name6"]}
]
I tried to go line by line in debugging JS mode, but it looks like the console simply leaps over the "new Swiper(..." line and everything inside it. Again, no errors in console.
How to feel really stupid:
Spend half a day figuring out why your code doesn't work
On a whim go check that your swiper selector class is attached to the correct html element and realize that it is not
Go cry in stackoverflow
I'm sorry guys, this question is useless. Everything works as intended with that d'oh fix.

Jquery tool tip is not showing with AJAX data load

I am having issue regarding the showing tooltip on the ajax loaded content, I am adding the tooltip to ul with a function, and trying to bind it with mouse over event as it works.
str += '<li><a href="#" class="tooltip-1" data-placement="top" data-original-title="' + _icon_list[2] + ':' + obj[_icon_list[1]] + '">' +
'<i class="' + _icon_list[0] + '"></i></a></li>';
after adding the data I am trying to bind it
$('a.tooltip-1').on({
"mouseover": function() {
tool_tip();
},
"mouseout": function() {
$(this).tooltip("disable");
}
});
function tool_tip() {
$('[data-toggle="tooltip"]').tooltip()
}
it's getting callback but not showing the tooltip? here is the link of theme which has the tooltip and i am using it with my dynamic content.
http://www.soaptheme.net/wordpress/citytours/shortcodes/
Where is your ajax function?
Just add a title="your tooltip text here" in your href and in you ajax callback call this command.
$('a.tooltip-1').tooltip( );

How to retrieve id from selected item using "this"

I am new at jQuery/javascript. I tried some suggestions I found on this forum but so far it did not help.
THis is what I am trying:
When loading categories from a database ( using ajax) this HTML statement is added for each category:
$("#Links ul").append('<li id=\"cat' + i + '" data-catid=' + i + '>' + categorie_tekst[1] + '</li>');
Using F12 I see that the lines are correctly added.
E.g. <li id="cat3" data-catid="3">Seafood </li>
Next step is selecting a category in the screen and retrieve the products of this category using the value set for data-catid.
I have been told that I could "this.id" but so far no luck. Displaying the value of this.id with alert returns the correct value but for some reason I can't use it.
When I add (#cat3).attr(“data-catid”) in the code it works. But different options like these did not work:
("#cat"+ this.id).attr(“data-catid”)
(this).attr(“data-catid”)
var x = $(this).id();
var rest = x.substr(4, 1);
Everything with "this" creates error : Uncaught TypeError: ("#cat" + this.id).attr is not a function...
Trying to display any of these options does not give any output (not even a popup when I set an alert)
Any help would be appreciated!
You are loading dynamic values. Please use Event Delegation. And the $.one() binds the event once.
You need to add this in your ready function.
$(document).ready(function () {
$("#Links ul").one("click", ".cat", function(){
alert($(this).data('catid'))
});
});
To get the IDs of the elements, use $(this).attr("id") or $(this).prop("id") (latest jQuery) instead of this.id, as sometimes, it might return the jQuery object.
As you are creating elements like
$("#Links ul").append('<li class="cat" id=\"cat' + i + '" data-catid=' + i + '>' + categorie_tekst[1] + '</li>');
create elements using jQuery
$("#Links ul").append( $('<li></li>', {
class: "cat",
id: "cat" + i,
data-catid: i,
text: categorie_tekst[1]
});
As you are creating elements dynamically use Event Delegation. You have to use .on() using delegated-events approach.
$(document).ready(function () {
$("#Links ul").on(event, ".cat", function(){
alert($(this).data('catid'))
});
});

Make a javascript function instead variables

Here I have a code that create a sidebar:
var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>" + '<div class="raty" />' + "</br>";
$(side_bar_html).appendTo('#side_bar').filter('.raty').raty({
score : place.rating,
path : 'http://wbotelhos.com/raty/lib/img'
})
How I can create a function from this code to create a sidebar with function ...
So something like that:
function Create_a_sidebar_and_put_it_into_ID#sidebar () {
//for every marker to return html string
return "<div class='element'>"+place.name+"</br>"+place.rating+"</div>" + etc...
Becouse I have a problem with creating html, I dont know what to append where and I dont have contol over that
Is it possible?
If I'm understanding your question correctly, you're asking how you can take your first code block that creates a rating for a certain place, and refactor it so that you can arbitrarily create sidebars for places at will. So that's how I'll approach this answer.
As #Sime Vidas mentioned, you can start by taking the code that creates the sidebar itself and making that a function such as that below. I've modified the function a bit to take the javascript out of the href attribute (which is generally considered a bad practice) and replaced passing an html string into $.fn.init (which I've found steeply degrades performance) with using DOM methods to create elements. You also don't need the <br /> after your a element because divs by default are block elements.
function createSidebar(place) {
var $sidebarLink = $(document.createElement('a'));
var $raty = $(document.createElement('div'));
$sidebarLink.attr('href', '#').text(place.name).click(function(evt) {
evt.stopPropagation();
google.maps.events.trigger(gmarkers[parseInt(gmarkers.length - 1, 10)], 'click');
});
$raty.addClass('raty').raty({
score: place.rating,
path: 'http://wbotelhos.com/raty/lib/img'
});
return $([$sidebarLink, $raty]);
}
Now you can do things like
var $sidebar = $('#side_bar');
places.map(createSidebar).forEach(function($sidebarPart) {
$sidebar.append($sidebarPart);
});
Sorry if I'm off track with answering your question, but I think this is what you were asking. If not feel free to leave a comment and we can talk about it more!

Categories

Resources