Call jQuery function in a loop with different parameters - javascript

I am trying to create multiple carousels in one page following this example.
I am creating my carousels in a foreach loop, and I assign to each carousel the names c0, c1, c2, etc. (Each carousel is a <div>)
Now, in order to run the script according to the example, I should run in on each carousel separately.
For example:
<script type="text/javascript">
$(document).ready(function() {
$('#c0').jsCarousel({ onthumbnailclick: function(src) { alert(src); }, autoscroll: true, masked: false, itemstodisplay: 3, orientation: 'v' });
$('#c1').jsCarousel({ onthumbnailclick: function(src) { alert(src); }, autoscroll: false, masked: false, itemstodisplay: 5, orientation: 'h' });
$('#c2').jsCarousel({ onthumbnailclick: function(src) { alert(src); }, autoscroll: true, masked: true, itemstodisplay: 5, orientation: 'h' });
});
</script>
Since my carousels are created in a foreach loop, I cannot know how many of them I will have, so I tried to call the function in a for loop:
for (int i = 0; i < counter; i++)
{
string cNum = "#c" + i.ToString();%>
<script type="text/javascript">
$(document).ready(function() {
$(cNum).jsCarousel({ onthumbnailclick: function(src) { alert(src); }, autoscroll: true });
});
</script>
<%} %>
I checked, and the cNum values are okay, it gets the values #c0, #c1, etc. but it can't recognize it as an equivalent to '#c0' etc. that were there initially.
How can I insert dynamic carousel names into the function?

Instead of doing that, just give each div a class. Like this:
<div class="someClassThatIKnowIsACarousel">
Then you don't need a loop:
$(".someClassThatIKnowIsACarousel").jsCarousel({ onthumbnailclick: function(src) { alert(src); }, autoscroll: true });

The problem in your code is that cNum inside your dynamically generated JavaScript section isn't interpreted as an ASP variable. You could fix that with something like $('<% cNum %>') (also note the JavaScript quotes, without get you would get $(#c0), which is erroneous).
However, your approach is wrong, please avoid the best you can mixing server/client code like that.
As aquinas already pointed out, the best solution is to add a class to the divs:
HTML:
<div class="carousel">
JavaScript:
$('div.carousel').jsCarousel({ ... });

Related

swiper.js controlling two instances

So I have setup two swiper.js instances and I want to scroll both while using one of them.
EDIT: My main goal is to recreate the main functionality on top of the swiper homepage.
EDIT2: I found this link, but it appears that this uses an older version of swiper.
Here is my config, only the first one works.
$(document).ready(function () {
//initialize swiper when document ready
var swiperFront = new Swiper('.swiper-container-front', {
// Optional parameters
effect: 'coverflow',
centeredSlides: true,
direction: 'horizontal',
slidesPerView: '3',
loop: false,
followFinger: true,
controller: {
control: [swiperFront, swiperBack],
by: 'container',
}
});
var swiperBack = new Swiper('.swiper-container-back', {
// Optional parameters
effect: 'fade',
centeredSlides: true,
slidesPerView: '3',
loop: false,
});
swiperFront.params.controller.control = swiperBack;
swiperBack.params.controller.control = swiperFront;
})
What am I doing wrong, and how to fix it?
Fiddle
I think the main problem here was the outdated swiper.js version. Updated to 4.3.2.
jsfiddle: https://jsfiddle.net/ajxmyL7v/
For documentation reasons.
For this case the main difference in switching from Swiper v3 to v4 is to omit the .params. So instead of
mySwiper.params.control
without params and the new API
mySwiper.controller.control

How to sync texts and photos in bootstrap?

I have a bootstrap site which has 3 photos in a slideshow. The function which does that is:
$(function () {
$.vegas('slideshow', {
backgrounds: [{
src: 'img/ph1.jpg', fade: 0, delay: 5000, //fade: 1000, delay: 9000,
}, {
src: 'img/ph2.jpg', fade: 0, delay: 5000,
}, {
src: 'img/ph3.jpg', fade: 0, delay: 5000,
},]
})('overlay', {});
});
What I want to do is to associate text for each photo. For example: for ph1.jpg to have "text1", for ph2.jpg to have "text2", and so on.
I tried to add a carousel in my HTML but the text and the photo are not synchronized (even if they have the same delay). I also tried to modify this JS so to be able to add some text in the above function.
What can I do to get them sync the photos and the text?
Try better to put your images in a css file and from there to put the text for each other.
You may try below code which rely on vegaswalk event callback.
vegaswalk event gets triggered whenever Vegas changes the slide. It can be utilized as follows:
var textArray = [
"text1 for ph1.jpg",
"text2 for ph2.jpg",
"text3 for ph3.jpg"
];
$("body").on('vegaswalk', function (e, index, slideSettings) {
var currentText = textArray[index];
alert(currentText);
//write here code to set this text in some div present on Page
//OR
//write code to move the slide of text carousel as per current index of slideshow
});

How do I encode HTML characters within Javascript functions?

to all Javascript experts this question might be just basics. I'm using jQuery and I am working on a tooltip created with jQuery.flot.
The following is a part of my javascript function within an html file and this is exactly what I need to have the tooltip div to be rendered correctly:
$('<div id="tooltip">' + contents + '</div>').css( {
Because the div is not shown I used Firebug to look for the reason and the line of code from above shows the special characters < and > encoded as html entities < and > as you can see here:
$('<div id="tooltip">' + contents + '</div>').css( {
I was searching several online sources for a solution and tried things like .replace(/lt;/g,'<') or .html().text() and it took me more than three hours but nothing was helpful.
I works fine on localhost.
Full Source Code:
<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.flot.categories.js"></script>
<![CDATA[
<script type="text/javascript">
$(function () {
var data = [ ]]>{e1Array}<![CDATA[ ];
$.plot($("#placeholder1"), [ data ], {
series: {
bars: {
show: true,
barWidth: 1,
align: "center"
}
},
grid: {
hoverable: true,
clickable: true
},
xaxis: {
mode: "categories",
tickLength: 0
},
yaxis: {
min: 0,
max: 1,
ticks: 0
}
} );
});
var previousPoint = null;
$("#placeholder1").bind("plothover", function (event, pos, item) {
if (item) {
if (previousPoint != item.datapoint) {
previousPoint = item.datapoint;
$("#tooltip1").remove();
showTooltip(item.pageX, item.screenY, item.series.data[item.dataIndex][0] + ': ' + item.series.data[item.dataIndex][1] + ' Einträge');
}
} else {
$("#tooltip1").remove();
previousPoint = null;
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: 100,
left: x,
border: '1px solid #fdd',
padding: '2px',
'background-color': '#fee',
opacity: 0.80
}).appendTo("#e1-container").fadeIn(0);
}
</script>
]]>
<div class="e1-container" id="e1-container">
<div id="placeholder1" class="e1"></div>
</div>
<![CDATA[
<script type="text/javascript">
This seems to be your problem, or at least the reason why FireBug does show html entities in your code. If you want to use cdata at all, you should place it inside of the <script> tags.
On why the tooltip is not shown at all, I can only guess, but for text content I'd recommend to use
$('<div id="tooltip"></div>').text(contents)
instead of using it as a html string.
You use appendTo(), which is fine.
You append the node only when the plothover flot event is fired.
This is correct, too.
So your code looks fine, you should probably look into this:
Jquery Flot "plothover" event not working
EDIT: You also can put the JS <script> after the HTML.
Do not directly add the contents inside the selector.
1) Create your DOM : var k = $('<div id="tooltip"></div>');
2) Fill your DOM :
// Add after
k.append(contents);
// Replace
k.html(contents);
// Replace and the content is just some text
k.text(contents);
3) Set the CSS : k.css({ ... })
4) Add the DOM to your page k.appendTo('#container');. You can also use $('#container').html(k); to replace the container contents and avoid to have a duplicate
In short :
var k = $('<div id="tooltip"></div>')
.append(contents)
.css({})
.appendTo('#container');
NOTE: The best way is to already create your tooltip div and just fill the elements to avoid to create two div with same ID, ... If you are afraid it perturbs the page, add display : none; to the CSS before to edit it, then change the classes when you edit it.
You will need to create div on 2 conditions :
The pages is created on load with variable number of components
You want to dynamically load CSS or JS.

Add tip text dynamically to a slider

In my project, I am trying to add the tip text (config) dynamically to a slider. How to do that?
I need to add it dynamically because I am generating the array of variables in a "Controller", which holds the text for each value of the slider (for tip text).
var slider = Ext.getCmp('slider')
slider.setTipText(arrayOfVariables) //What should I do here instead?
There is no such method like setTipText in docs. What should I use then?
EDIT:
{
xtype:'slider',
animate: false,
//plugins: [Ext.create('App.view.SliderOverride')],
cls: 'sliderStyle',
width: "80%",
id: 'slider',
value: 36/2, //must be current month
//increment: 10,
minValue: 1,
maxValue: 36,
useTips: true,
tipText: function(thumb){
alert("hello");
App.getController('TaskController')._arrMonthView[thumb.value].month;
},
},
tipText requires a function config so you can add a function that will use your variables from controller;
Ext.create('Ext.slider.Multi', {
....
tipText: function(){
return App.getController('your controller').yourVariable
},
.....
});
This is added on the creation of the slider so you don't need to modify it , just your variables in controller. So you don't need to re set the tip text function.
I solved this issue by using getText method of Ext.slider.Tip.
Used to create the text that appears in the Tip's body. By default this just returns the value of the Slider Thumb that the Tip is attached to. Override to customize.
For example in which situation it can be used, you have a look at this link

How to dynamically create multiple jQuery sliders?

I am working on a WordPress site that turns a custom post type into a slider on a page. I am using Sequence.js for my slider and I can manually create multiple sliders no problem with the following:
//sequence slider options to be used by slider1
var options0 = {
sartingFrameID: 1,
cycle: true,
autoPlay: false,
nextButton: '.next0',
prevButton: '.prev0',
fallback: {
theme: "fade",
speed: 100
}
}
//slider1
var sequence0 = $(".slideContainer0").sequence(options0).data("sequence");
//sequence slider options to be used by slider2
var options1 = {
sartingFrameID: 1,
cycle: true,
autoPlay: false,
nextButton: '.next1',
prevButton: '.prev1',
fallback: {
theme: "fade",
speed: 100
}
}
//slider2
var sequence1 = $(".slideContainer1").sequence(options1).data("sequence");
How can I streamline this? And also make it dynamic so a slider is created for each post that is made? Any help would be greatly appreciated.
edited - added working answer
I used the answer from Cymen below for the first part by turning the options output into a function and simply calling the function with a counter for each sequence instance. Then used the second part of his answer to initialize each sequence slider and it works a treat.
This is what I have working now:
function options(number) {
return {
startingFrameID: 1,
cycle: true,
autoPlay: false,
nextButton: '.next' + number,
prevButton: '.prev' + number,
fallback: {
theme: "fade",
speed: 100
}
};
}
var count = 0;
$('.slideContainer').each(function() {
var sequence = $(this);
sequence.sequence(options(count)).data('sequence');
count++;
});
I haven't used sequence but from your post I am guessing you want to be able to recreate the options object with an increment of the number. So you could do something like this:
function options(number) {
return {
startingFrameID: 1,
cycle: true,
autoPlay: false,
nextButton: '.next' + number,
prevButton: '.prev' + number,
fallback: {
theme: "fade",
speed: 100
}
};
}
Then use it like so:
$(target).sequence(options(0)).data("sequence");
Or in your specific example:
//slider1
var sequence0 = $(".slideContainer0").sequence(options(0)).data("sequence");
//slider2
var sequence1 = $(".slideContainer1").sequence(options(1)).data("sequence")
And to do what you are talking about how about giving all the sequences the same class like say custom-sequence and then do something like this:
var count = 0;
$('.custom-sequence').each(function() {
var sequence = $(this);
sequence.sequence(options(count)).data('sequence');
count++;
});
That may or may not work -- it isn't quite clear to me what the .data('sequence') is doing.

Categories

Resources