append and remove elements on upcount and downcount - javascript

I've a question on the jQuery UI Slider widget. What I intend to do is, that on every upcounting value the slider appends me an image in a div:
$("#divOne").slider({
range: "min",
min: 1,
max: 10,
slide: function (event, ui) {
console.log(ui.value);
if(ui.value == 1) {
$('#divOne').append('<img class="linkimg" src="img/link/zwei.png">');
}
if(ui.value == 2) {
$('#divOne').append('<img class="linkimg" src="img/link/drei.png">');
}
if(ui.value == 3) {
$('#divOne').append('<img class="linkimg" src="img/link/eins.png">');
}
},
change: function (event, ui) {
//alert('Stopped at ' + ui.value);
}
});
works good so far.
The problem is, I want to remove the elements if I'm then downcounting but then if I cross one number it of course appends again, so I guess compare the value in that if-statement is wrong.
Does anyone of you has a hint? Cheers
EDIT: I have made an image to show what I want to do CLICK

Assume placing all the images in html
/* cache collection of images*/
var $images= $("#divOne img")
$("#divOne").slider({
slide:function(e,ui){
if( ui.value !== $images.filter(':visible').length){
$images.hide().slice( 0, ui.value).show();
}
}
});
What this does is track number visible vs slider value.... if they don't match it hides all and shows the ones that match slider.
If you have a large number... this should be upgraded to track direction of slider and only modify affected images to improve performance

First change the image names to match the values. E.g., 1.png, 2.png. Then you can:
var i, maxVal = ui.value, html='';
for (i = 1; i <= maxVal; i += 1) {
html += '<img src="img/' + i + '.png';
}
$('#divOne').html(html);
EDIT: But in general a better approach is to have all images in the container and then construct a stylesheet that would map classes that match values to appropriate state. E.g.:
<div class="score[X]"> <!-- where `[X]` will be the actual value of the ui.value -->
<img class="val1" src="1.png">
<img class="val2" src="2.png">
<img class="val3" src="3.png">
</div>
In css:
.score1 .val2 { display: none; }
.score1 .val3 { display: none; }
....
Or some other variation of the above.
EDIT:
Example fiddle with a slightly different approach for CSS: http://jsfiddle.net/gwQAW/
EDIT2:
And version with HTML5 slider: http://jsfiddle.net/gwQAW/2/ (sorry, no time for jQuery UI right now)

Related

Adding click event to JQ slider

This is the webiste I run : http://bit.ly/1a3lbaf
The image slider was made in jq javascript by the guy who originally created the website and I'd like some help to add working links on the <li><a> triggering the animation of the script.
Here is the code I have :
<script type="text/javascript">
//<![CDATA[
jq(document).ready(function(){
if ( jq('#slider-home ul#slider').length == 1 && jq('#slider-home ul#slider li').length > 1 ){
var homeslidenav = new Array([!YAMS? &get=`tv` &from=`nav-slider`!]);
jq.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) {
jq(pager).each(function() {
jq(this).children().removeClass(clsName).eq(currSlide).addClass(clsName);
});
jq('#navwh').stop(true, true).css('width', currSlide * 138).animate({ width: '+=138' }, 4800 );
};
jq('#slider-home ul#slider').cycle({
fx : 'fade',
pause : true,
pager : '#nav-menu',
pagerEvent : 'mouseover',
timeout : 4000,
activePagerClass : 'active',
onPagerEvent : function(a){
jq('#navwh').css('width', a * 138).animate({ width: '+=138' }, 4800 );
},
pagerAnchorBuilder: function(idx, slide) {
var chtml = '<li id="hotel' + (idx + 1) + '"';
if (idx == 0) chtml += ' class="first"';
chtml += '>' + homeslidenav[idx] + '</li>';
return chtml;
}
});
}
});
//]]>
</script>
I've been able to change the pageEvent from click to mouseover as I find it more practical. Now I'd like to preserve the animation but in the same time add working links instead of the useless <a href="#"> in the <li>. I've tried putting an actual url in the <a href="#"> but it doesn't work as I suppose the onPagerEvent overrides the <a> (I'm not fluent in js as you might have noticed).
Could someone please help me find a way to add this working links ?
Thanks in advance.
onPagerEvent is not doing anything to your links - it is just adjusting the width of the white bar that goes along the bottom of the images (that indicates how long until the next image shows)
The site is using the jQuery cycle plugin - you can find the documentation here: http://jquery.malsup.com/cycle/
The updateActivePagerLink function is what is responsible for updating the links (by the way, I visited the site and the links appear to be working - are you trying to add more links?) The links themselves are coming from the list items inside the <ul id="slider">, like this:
<li style="position: absolute; top: 0px; left: 0px; display: none; z-index: 7; opacity: 0; width: 966px; height: 390px;"><img src="/assets/images/groupe/sliders/SliderHome-3_en.jpg" alt=""></li>
To add a new image with a link, just add a new <li> with the format above (and with the correct href in the <a>) - you don't need to modify any JavaScript code.

jQuery Click event works only once (none of the previous Stack Overflow answers helped)

What I'm trying to do is that when the page loads I'm resetting an image to my desired small size.
If the user clicks on the image later it should enlarge with an animation, I'm done up to this part.
When the user again clicks on that image it should be resized to the size that I assigned after loading the page, I have tried toggle event, but that's not working, toggle just makes my images disappear from the page. So I created an alternate to toggle event by using if and else condition and a flag variable called "small" but the problem is that click event is working only once i.e: If the image is in the small size and I click on it, the image gets enlarged but when I click on it again the click event is fired but it doesn't work, I wish if there is any way that I could make it work with toggle event, otherwise I would like to do it by using if and else condition in click event.
Here's the HTML:
<html>
<head>
<title></title>
<script src="jquery-1.10.1.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<img src="wordpress.jpg" class="small-Img" id="test"> <br>
<img src="store.jpg" class="small-Img">
</body>
</html>
Here's the script:
$(document).ready(function() {
var small;
$('.small-Img').on('load',function(){
$(".small-Img").attr('width','200');
small=Number(1);
});
$('.small-Img').on('click',function () {
alert("event fired");
if(small==1){
var obj=$(this);
var originalWidth=obj[0].naturalWidth;
var originalHeight=obj[0].naturalHeight;
$(this).animate({ height: originalHeight, width: originalWidth }, 1000, function() { });
small=Number(0);
}
if(small==0){
$(".small-Img").attr('width','200');
small=Number(1);
}
});
});
Your code
$(".small-Img").attr('width','200');
sets a width attribute on the image, similar to <img src="url" width="200"> which probably doesn't result in a size change. Try
$('.small-Img').css('width','200px');
or animate the shrinking
$('.small-Img').animate({ width: '200px' }, 1000);
You may also get better results making small an attribute of your image rather than a property of the window object
jsfiddle
It sounds like the problem isn't that the event isn't fired multiple times, but that it doesn't enter your if statement. Try making small a boolean variable instead of a number, that way you can avoid all the == vs === messyness
EDIT:
Also, you probably want an else if so that it doesn't shrink once it enlarges on each click.
DEMO
for setting or getting css value we use .css() not .attr()
== only checks the value
=== checks the value and the datatype
$(document).ready(function () {
var small;
$('.small-Img').on('load', function () {
$(".small-Img").css('width', '200'); //changed attr to css
small = 1;
});
$('.small-Img').on('click', function () {
if (small === 1) { //changed == to ===
var obj = $(this);
var originalWidth = obj[0].naturalWidth;
var originalHeight = obj[0].naturalHeight;
$(this).animate({
height: originalHeight,
width: originalWidth
}, 1000, function () {});
small = 0;
}
if (small === 0) { //changed == to ===
$(".small-Img").css('width', '200'); //changed attr to css
small = 1;
}
});
});
How about first making "small" a data-attribute on the image itself? Not a big deal, but a little more convenient (IMHO). The next thing is, when you want to check the second click, you might consider doing an else if rather than just an if. Not sure if it makes a difference, but it is a clear logical differentiation, you can have one or the other -- not both. Third, if you animate the width back down, you might also animate the height, calculated by your small height divided by your original height times the original width. Seems to work, see it here: http://jsfiddle.net/snowMonkey/7nCMF/1/
$('.small-Img').css('width','200px').data("small", 1);
$('.small-Img').on('click',function () {
var that=this;
this.smallWidth = "200px";
this.smallHeight = (200/$(this)[0].naturalWidth) * $(this)[0].naturalHeight+"px";
if($(this).data("small")===1 ){
var obj=$(that);
var originalWidth=obj[0].naturalWidth;
var originalHeight=obj[0].naturalHeight;
$(that).animate({
height: originalHeight,
width: originalWidth
}, 1000, function() { });
$(that).data("small",0);
} else if($(this).data("small")===0){
$(that).animate({
width: that.smallWidth,
height: that.smallHeight
}, 1000, function(){}).data("small", 1);
}
});
Best of luck!

How can I optimize jQuery functions for a large amount of HTML elements

I work on a climate model and I display it on a map grid. I have to use a large grid : 39x60.
So I have to manage 2340 <div> with jQuery. I want to use a jQuery slider to zoom in / out with this :
$("#zoom_slider").slider({
orientation: "vertical",
value: 1,
min: 1,
max: 10,
step: 1,
slide: function( event, ui ) {
$('.case').css('width', function(index) {
return index * ui.value;
});
$('.case').css('height', function(index) {
return index * ui.value;
});
}
});
Each cell is built as this example :
<div id="c13_53" class="case line_13 col_53" style="width: 17px; height: 17px; top: 216px; left: 937px;"></div>
But firefox crashes when the function is executed.
Is there a way to fix this problem ?
One inefficiency in your code is that you're re-selecting every div on every slide event twice. $('.case') forces the scan of the entire DOM. You should cache the elements in a variable and reuse that variable instead of re-scanning constantly.
Another inefficiency may be that multiple slide events could be getting fired as you slide; putting a throttle on your handler could speed things up.
Was it your intention to set each one larger by what index it has? That will mean no matter which way the slider goes they will get bigger, much bigger. Better to store a reference value I think.
//Size in pixels.
var originalSize = 20,
cases = $('.case');
stop: function(_, ui) {
var size = ui.val * originalSize;
cases.css({width: size + 'px', height: size + 'px'});
}
Used stop as per Jacobs suggestion.
This will at least make it more efficient, as to whether it stops crashing, no idea.

Help with adding CSS to jquery

I am really new to jquery and I dont really have time to see how it works (I work with PHP a lot) I want to make a jquery slideshow but I dont know how to add z-index to the images here: http://www.albavid.com/new/index.html
I can see that jquery adds some css elements like opacity, width.. etc.
I tried to add a bigger z-index to the current image and lower z-index to the right images and left images.
Can anyone tell me how to add css with jquery so the current image(the biggest) to be on the top and then the others behind it.
Replace your javascript on the page with this:
I added in $(el).css('z-index', 5) and $(el).css('z-index', 0) in currentCss, beforeCss, and afterCss.
jQuery( document ).ready( function(){
jQuery( '#flip' ).jcoverflip({
current: 2,
beforeCss: function( el, container, offset ){
$(el).css('z-index', 0);
return [
$.jcoverflip.animationElement( el, { left: ( container.width( )/2 - 210 - 110*offset + 20*offset )+'px', bottom: '20px' }, { } ),
$.jcoverflip.animationElement( el.find( 'img' ), { width: Math.max(10,200-10*offset*offset) + 'px' }, {} )
];
},
afterCss: function( el, container, offset ){
$(el).css('z-index', 0);
return [
$.jcoverflip.animationElement( el, { left: ( container.width( )/2 + 110 + 110*offset )+'px', bottom: '10px' }, { } ),
$.jcoverflip.animationElement( el.find( 'img' ), { width: Math.max(10,200-10*offset*offset) + 'px' }, {} )
];
},
currentCss: function( el, container ){
$(el).css('z-index', 5);
return [
$.jcoverflip.animationElement( el, { left: ( container.width( )/2 - 200 )+'px', bottom: 0 }, { } ),
$.jcoverflip.animationElement( el.find( 'img' ), { width: '400px' }, { } )
];
},
change: function(event, ui){
jQuery('#scrollbar').slider('value', ui.to*25);
}
});
jQuery('#scrollbar').slider({
value: 50,
stop: function(event, ui) {
if(event.originalEvent) {
var newVal = Math.round(ui.value/25);
jQuery( '#flip' ).jcoverflip( 'current', newVal );
jQuery('#scrollbar').slider('value', newVal*25);
}
}
});
});
you can also get it working by using different classes the use addclass() - removeClass() to toggle the effect works well if you're already familiar with CSS overrides
Try setting the position property of the elements to relative, otherwise they will be treated as static and ignore all settings to z-index.
It looks like the z-index in question should be applied to the <li>, not the <img>.
You can alter the z-index of an element by using the .css() function.
$("#elem").css('z-index','1000');
However, two better options would be to either define CSS classes for the elements you want to style and toggle between them, or use some nice jQuery slideshow plugins.
You can alter the inline CSS by selecting the element and using the css method
Suppose an element has no z-index, or a different one, and you want to change it to 5
$("#elementId").css('z-index', 5);
Another option is to set up classes with certain CSS styles before hand and change the class of certain elements ie (currentShown, nextUp, etc)
rather then waste your time reinventing the wheel why not just use a jquery slideshow plugin?
Z-index'ing the <li> instead of the <img> is the right solution to fix the overlap. However, because the <li>s are dynamic and flip before and after each other, an applied z-index to all in a sequential order from left-to-right will not solve his issue.
Solving the issue will need a few more actions to invoke within jquery but not too much extra work. What needs to happen is for jQuery to apply a z-index to the current <li> higher than the rest of the batch for each event on the slider.
Since I don't have access to your code, you basically want to apply the following logic:
Whatever <li> is in front it should have a z-index:1 and all other <li>s should have z-index:0. This should happen on every change in the slider.
#mcgrailm: Give him a break man, you can't learn how to swim unless you jump into the pool.

How to display the current slider value on the jQuery slider knob?

I'm trying to figure out from the jQuery example here whether it's possible to set the current value of the slider as text that appears on the slider knob.
So, as the user changes the slider, the new value would continually update as a number value displayed as text on the surface of the slider knob in real time.
$(document).ready(function() {
$("#slider").slider();
});
<div id="slider"></div>
Is there a way to do that?
#EvilMM's answer is almost right but s/he forgot the quotes and I've also experienced the slider value being -1 so I wrote in a fix for that.
<div id="slider"></div>
js:
$("#slider").slider({
max: 10,
slide: function (event, ui) {
m_val = ui.value;
if (m_val < 0) {
m_val = 0;
$(this).slider({ value: 0 });
}
$(this).find("a:first").text(m_val);
}
});
Lets say your slider is called "slider", just like in you example:
<div id="slider" class="slider"></div>
Then, inside this div, there is a generated link-tag (a) that represents the knob.
So you could try something like that:
$(document).ready(function() {
$("#slider").slider(
slide: function(event, ui){
$("#slider").find(a:first).text(ui.value);
}
);
});
This should write the current value on the knob while sliding.
What you now have to do, is to play around with the css to format the knob.
I hope this will help a little bit.
If you are using Jquery UI
$(function(){
var slider = $('#slider1').bxSlider({
onBeforeSlide: function(currentSlide, totalSlides){
alert(currentSlide);
}
});
Done!

Categories

Resources