I am trying to create a very simple image slider. As simple as it gets but the way I'm doing it I'm having to enter too many combinations.
This is what I've got:
<script>
$(document).ready(function(){
$('#1').show();
$('#2').hide();
$('#3').hide();
$("next-btn").click(function(){
$("#1").hide();
$("#2").show();
});
});
</script>
</head>
<body>
<div id="slider">
<div id="1" class="slide"><img src="slide-image-1" alt="" /></div>
<div id="2" class="slide"><img src="slide-image-2" alt="" /></div>
<div id="3" class="slide"><img src="slide-image-3" alt="" /></div>
</div>
<div id="previous-btn">Previous slide</div>
<div id="next-btn">Next slide</div>
As you can see by the jquery code, the way I'm going i'll have to enter different onclick's depending which image is hidden etc..
How can I change this so it can just go to the next or previous div and show it when either buttons are clicked without having to add too many combinations?
This code should work OK (tested). I hope you will get the idea :).
<script>
var active = 0;
var n = $('#slider div').length; // number of divs...
$(document).ready(function(){
showElement(1);
$("#next-btn").click(function(){
if (active < n) showElement(active + 1);
});
$("#previous-btn").click(function(){
if (active > 1) showElement(active - 1);
});
});
function showElement(id) {
$('#slider div').hide();
$('#' + id).show();
active = id;
}
</script>
active stores the number of element that is showed. When you show something else, you hide everything, and show only the one you need. n is used to store maximum number of elements so you will not get out of scope.
By the way this is not the most memory efficient solution, but it is really simple to modify it and it is really flexible. To be honest, you should track which slide is showed, which is hidden, and hide only the one that is showed, and show only the one that You need. But if there are only few slides (100?), the performance gap wont be a problem here, while the clarity of code and future expandability is much better here.
Also if something will go wrong in the future, every time user clicks something, the showElement function will repair it: hiding everything, and showing only the one you need.
Take a look on a working solution under this link: http://codepen.io/anon/pen/XbPogg
BTW: You can add more slides (id = 1, 2, 3, 4, 5, 6, ...) in your html markup, and this script will work without of any changes.
Related
I'm sure this is a pretty common question around here but after lots of research I can't seem to find an answer to my question.
So just a little warning; I'm really new into javascript and jQuery etc.
To the question! I'm trying to apply two images (It's img's that looks like buttons :P) which you click on and it scrolls to the "next" paragraph or div.
So to get an overview of how it looks, here' a part of the HTML:
<div id="scrollbuttons">
<img id="prev" src="pics/prev.png"></img>
<img id="next" src="pics/next.png"></img>
</div>
Also:
<div id="work">
<p class="maintext">blabla</p>
</div>
<div id="gallery">
<p class="maintext">blabla</p>
</div>
<div id="project">
<p class="maintext">blabla</p>
</div>
<div id="finish">
<p class="maintext">blabla</p>
</div>
So what I'm trying to create is when you click on "next", the page should smoothly and automatically scroll to firstly, "work", then to "gallery" etc.
And when you press "prev", the page should again smoothly and automatically scroll back to the previous point.
I have the latest jQuery version and I'd like to not install plugins if it's not absolutely needed.
So I hope this is enough info to get some help, I'd really appreciate it since I'm really new to JS.
Thanks in advance
/Emil Nilsson
Here you go, this could probably be done a little more efficiently but it's dynamic and it works. Click the buttons to go forward and backward. FYI I added a mutual class called section to all of your content divs
JSFIDDLE
var Section = "start";
$("#next").click(function(){
if(Section == "start"){
var nextSection ="work";
}else{
var nextSection = $("#"+Section).next(".section").attr("id");
}
$("html, body").animate({scrollTop: $("#"+nextSection).offset().top});
Section = nextSection;
});
$("#prev").click(function(){
var nextSection = $("#"+Section).prev(".section").attr("id");
$("html, body").animate({scrollTop: $("#"+nextSection).offset().top});
Section = nextSection;
});
maybe you need something like this
http://jsfiddle.net/urUFK/
the img would be inside of the anchor like this (semantics and W3C validation):
<img id="prev" src="pics/prev.png"></img>
on my version you just need to define the first element and the div id's
This show-hide function attempts to do so anonymously, without the need to maintain unique IDs for the target divs.
I am having trouble understanding why my selector for the var div does not work in example #4, and how I may be able to get it working for all examples shown.
$('.expander').click(function(e)
{
e.preventDefault();
var div = $(this).nextAll('div.content').first();
if (div)
{
if (div.css('display') == "none")
{
div.show();
$(this).removeClass("closed");
$(this).addClass("open");
}
else
{
div.hide();
$(this).removeClass("open");
$(this).addClass("closed");
}
}
});
<div>
example 1<br />
<div class="content open">shown content</div>
example 2<br />
<div class="content closed">hidden content</div>
example 3<br />
<!-- comments -->
<span>other content</span>
<div class="content closed">hidden content</div>
<p>
<span>
example 4
</span>
</p>
<div class="content closed">content</div>
</div>
The first three examples work fine. But when I deployed this code, I found there were variations in how the anchor may be coded. I am looking for a solution that works regardless of how the anchor is encapsulated.
The bottom line is I want to select the next div.content to the anchor, regardless if it is next, or if jQuery must walk up the DOM tree a little to find it.
I have a working model of this code here.
Because you anchor is nested inside a span which again nested inside a ptag
And this does not make sense in case of example# 4
var div = $(this).nextAll('div.content').first();
For example#4 you need this selector
var div = $(this).closest('p').nextAll('div.content').first();
I got this working walking up the parent tree until I see the next target div.
var div = $(this).nextAll('div.content').first();
if (div.length == 0)
{
div = $(this).parentsUntil('body').nextAll('div.content').first();
}
I don't really like the conditional, but unless I find something more elegant, I'll stick with this.
So I'm trying to have an effect that when you click on an image, two more images (stored in #sharebar) will slide out from the left. The issue is currently when the images slide out, they slide from the left under the button, and then shift up after the animation is complete. I would like everything to be on the same level the whole time, so that the images appear to slide out from behind.
Can anyone help me out? Here's what I have:
<script>
$(function() {
// run the currently selected effect
function slideOut() {
var options = {};
$("#sharebar").toggle("slide", options, 500, callback() );
};
function callback() {
};
// set effect from select menu value
$( "#download_link" ).click(function() {
slideOut();
return false;
});
$("#sharebar").hide();
});
</script>
</head>
<body>
<div style="margin:200px;min-height:10px;background:#e9e9e9;overflow:hidden;">
<img id="download_link" src="Download.png" style="z-index:2;"/>
<span id="sharebar" style="width:20px;z-index:1;">
<img id="exercise_link" src="exercises.png" />
<img id="subtitles_link" src="subtitles.png" />
</span>
Thanks in advance! :)
EDIT: I think this may have to do with z-index, but I'm not quite sure
I would definitely say z-index is going to be the way to go. It looks like you have some z-index things set already; just fix your z-index so the images layer on top of each other like you want them to.
<img id="download_link" src="Download.png" style="z-index:2;"/>
<span id="sharebar" style="width:20px;z-index:0;">
<img id="exercise_link" src="exercises.png" style="z-index:1" />
<img id="subtitles_link" src="subtitles.png" style="z-index:1" />
Just as a side-note: You're better off sticking these style attributes in a CSS document, rather than putting them in your HTML markup.
Setting the "top" element to have style="position:fixed" fixed the problem!
EDIT: Haha not sure why there's a downvote, it ended up fixing the problem.... :P
I am looking to implement a mouseover event on my page for a menu -
I have 3 titles to the left with a respective content div on the right where the related text appears.
Having trauled all the forums for a working js solution, I have settled with:
http://flowplayer.org/tools/demos/tabs/mouseover.html
which uses a very simple js function:
$("#products").tabs("div.description", {event:'mouseover'});
What I am hoping to do however, is to incorporate a fadeIn(), fadeOut effect so that when the user hovers over a title on the left of the page, the existing content showing fades away and the repective content will fade in to view......
The html coding is:
<div id="products" >
<img src="home.png" alt="home" />
<img src="services.png" alt="services" />
<img src="contact.png" alt="contact" />
</div>
<div class="description" id="home" >
.. content ..
</div>
<div class="description" id="services" >
.. content ..
</div>
<div class="description" id="contact" >
.. content ..
</div>
I have tried to incorporate thread 5404775 on this site but simply cannot get it working!
Any help much appreciated
The below can be seen on jsfiddle.
You can fade them in and out on mouseover like this
var _current = "home"; // default state
$('#products img').mouseover(function (){
// The one we want to show now
var id= $(this).attr('alt');
// We don't need to do anything if it's the same one that's already
// there
if (_current !== id){
$('#' + _current).fadeOut(function(){
// Fade in the new one after the old fades out
$('#' + id).fadeIn();
// Update state
_current = id;
});
}
});
I also added some thing to make sure that only the one you want displayed first is displayed when the page loads. I'm assuming it would be the home div.
Add this to the CSS
.hidden{
display:none;
}
and put that class on the other divs.
<div class="description hidden" id="services" >
.. services..
</div>
<div class="description hidden" id="contact" >
.. contact ..
</div>
I'm working off the assumption that you want people hovering over the image buttons here to make the corresponding divs fade in and out. What they are doing on that site will not work because Javascript is needed for the fading effect. JQuery makes this easy.
I recommend trying something like
<script type="text/javascript">
oldSelected = "home"
$(document).ready(function(){
$("#products img").mouseover(function(){
$(".description").stop(true, true);
var newSelected = $(this).attr("alt");
$("#" + oldSelected).fadeOut('normal',function(){
$("#" + newSelected).fadeIn();
});
oldSelected = newSelected
});
});
</script>
I have tested this and it works. One thing you will want to make sure of is that the css for the divs has them set to not be visible at the start, unless you want one of them visible in which case the id for that div should be what you set the oldSelected to at the start of the function.
Enjoy!
This might work:
$("img", "#products").hover(function() {
var id = $(this).attr("alt");
$("#" + id).fadeIn("slow");
}, function() {
var id = $(this).attr("alt");
$("#" + id).fadeOut("slow");
});
Another idea (without Jquery): you could use CSS opacity:x property (for firefox) or filter:alpha(opacity=x) (for IE) to change the opacity of an element. Fade in/out can be obtained with a small slowed-down cycle.
See also:
http://www.w3schools.com/css/css_image_transparency.asp
After cobbling together a few questions I've managed to get this far to showing / hiding divs:
$(document).ready(function(){
$('.box').hide();
$('#categories').onMouseOver(function() {
$('.box').hide();
$('#div' + $(this).val()).show();
});
});
HTML:
<div id="categories">
<div id="btn-top20">Top 20 Villas</div>
<div id="btn-villaspec">Villa Specials</div>
<div id="btn-staffpicks">Our Staff Picks</div>
</div>
<div id="category-content">
<div id="divarea1" class="box">
Content 1
</div>
<div id="divarea2" class="box">
Content 2
</div>
<div id="divarea3" class="box">
Content 3
</div>
</div>
What am I missing?
This will work:
<div id="btn-top20" rel="area1">Top 20 Villas</div>
<div id="btn-villaspec" rel="area2">Villa Specials</div>
<div id="btn-staffpicks" rel="area3">Our Staff Picks</div>
with this code:
$(document).ready(function(){
$('.box').hide();
$('#categories div').mouseenter(function() {
$('.box').hide();
$('#div' + $(this).attr('rel')).show();
});
});
Corrections:
No such function onMouseHover.
Attached the event to every div, not the #categories parent, so this has the right context.
added rel for every div, because val is meaningless.
Working example: http://jsbin.com/ivuxo
You may also want to hide the div on mouse out, in wich case you can use hover:
$('#categories div').hover(
function() { //hover in
$('.box').hide();
$('#div' + $(this).attr('rel')).show();
}, function(){ //out
$('.box').hide();
});
Flexible, generic (and untested!) solution which works with any number of "tabbed" element groups. You just need to specify ".tab-handles a[href=#id_of_target_tab]" hierarchy. As a bonus, the selected tab is remembered between page loads.
$(function() { // Shortcut for $(document).ready()
$('.tab-handles a').mouseenter(function() {
// Trigger custom event 'hide' for sibling handles.
$(this).siblings().trigger('hide');
// Show current tab.
$($(this).attr('href')).show();
}).bind('hide', function() {
// Hide the corresponding tab on custom event 'hide'.
$($(this).attr('href')).hide();
}).each(function() {
// Show tab if its id is found in url as an anchor (or hash).
if (new RegExp($(this).attr('href') + '$')).test(window.location.href))
$(this).trigger('mouseenter');
});
})
Your page can contain any number of the following structure:
<ul class="tab-handles">
<li></li>
<li></li>
</ul>
<div>
<div id="top-villas"> Your tab content goes here. </div>
<div id="villa-specials"> ... </div>
</div>
onMouseOver isn't a valid jquery method, among other things.
I really recommend browsing with google chrome when you're looking to debug javascript, it's error console is very useful for not just determining errors like this, but also for pinpointing the location in the script that is throwing the error, which might be an advantage beyond Firebug in firefox.
(And you can always run firebug lite as well via the bookmarklet even while using chrome, as the firebug lite website will show: http://getfirebug.com/firebuglite)
I used this to toggle my divs:
html
<div class="content-item-news">..</div>
<div class="content-news-extra">...</div>
jquery
$(".content-item-news").click(function() {
$(this).next(".content-news-extra").slideToggle(100);
});
I know this has already had a decent answer and although this isn't jQuery/mooTools - I figured it was worth a mention:
Seven Ways To Hide An Element With Javascript:
http://www.dustindiaz.com/seven-togglers/
:)