JQuery/JS function not firing on <a> - javascript

I have five slide shows on one page and I want to be able to cycle through all of them. The slideshow is made of an UL with each a different ID, so I want to create two functions for the arrows to cycle through the slides. And I want to pass the slide ID. My code:
$(document).ready(function() {
var slides = document.querySelectorAll('#slides li');
var slidesTotal = $('#slides li').length;
var currentSlide = 1;
function nextSlide() {
//$('a.nextSlideArrow').click(function() {
$('#slides .slide' + currentSlide).hide();
currentSlide++;
if(currentSlide > slidesTotal) {
currentSlide = 1;
}
$('#slides .slide' + currentSlide).show();
//return false;
//});
}
function previousSlide() {
//$('a.previousSlideArrow').click(function() {
$('#slides .slide' + currentSlide).hide();
currentSlide--;
if(currentSlide == 0) {
currentSlide = slidesTotal;
}
$('#slides .slide' + currentSlide).show();
//return false;
//});
}
});
<div id="slider-container">
<ul id="slides">
<?php
for ($i = 1; $i <= $amountImagesSlideshow[3]; $i++) {
echo '<li class="slide'.$i.'"><img src="'.$directories[3],$i.'.jpg" /></li>';
}
?>
</ul>
<div class="galleryPreviewArrows">
❮
❯
</div>
</div>
Now the funny thing is, if I remove the comments where the click is on the jQuery object and comment out the function, it will work. But not this way? I don't understand.

There is a difference between onclick event and functionality of href attribute.
When you write like this:
❮
It means, you are hyper referencing(trying to redirect) to some location whenever this anchor tag is clicked.
It doesn't mean you are doing only click action. It means, you are doing click + redirection.
href = click + redirection.
whereas, your need is only click event handling. Therefore, how you are handling through jquery.
$('a').on("click",function(){
----
----
})
This will work fine.

You shouldn't be using href to try to access a javascript function. That attribute is for navigation purposes. Also, binding to a jquery click even is the better way to handle your events so you adhere to separation of concerns design patterns.
If you need to put your function call in an attribute decorator, use the onclick attribute instead and don't evaluate the function by adding the parenthesis, just reference it.
<a onclick="previousSlide" class="previousSlideArrow">❮</a>

Anchor tag is for navigation which requires Href attribute. You should not use href for event handling. Instead:
<div class="galleryPreviewArrows">
❮
❯
</div>

It is strange..But writing that function outside document.ready works. It looks like that function should be defined before document is ready.
That may be the reson alert works always..which is a built-in function.
Also this is not the recommended way to bind event listner. Use jquery on/off to add/remove listners.
function nextSlide() {
//$('a.nextSlideArrow').click(function() {
alert('next');
//return false;
//});
}
function previousSlide() {
//$('a.previousSlideArrow').click(function() {
alert('prev');
//return false;
//});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider-container">
<div class="galleryPreviewArrows">
❮
❯
</div>
</div>

Related

Jquery change variable on click

Right, what I'd like to happen is when a button (or in this case, some text) is pressed, Jquery shows a div tag that contains an image, fades out the image after 2 seconds then displays some text.
This all works nicely, however I only want it to work once.
I decided to do this by using a variable and an if statement, so the variable changes from 0 to 1 and then the button cannot be clicked again due to the variable being changed.
Or at least, that's the badly worded version.
Anyhow, this is what I have so far, but for some reason the variable won't change from 0 to 1 after the button has been clicked, other than that, it works well.
The JS:
$(document).ready(function(){
$("#text2").css("display","none");
$("#ltt").css("display","none");
var clicked = '0';
if(clicked == 0) {
$(".clicker").click(function() {
$("#ltt").fadeIn("slow");
$('#ltt').delay(2000).fadeOut('slow');
$("#text2").delay(3000).fadeIn(1000);
$clicked = '1';
});
}
});
The HTML:
<div class="clicker">
click to see text
</div>
<div id="ltt">
<img src="Images/LoadingCircle.gif" width="24" height="24">
</div>
<div id="text2">
SOME TEXT
</div>
Try to use .one() in this context,
$(".clicker").one('click', function() {
$("#ltt").fadeIn("slow");
$('#ltt').delay(2000).fadeOut('slow');
$("#text2").delay(3000).fadeIn(1000);
});
You should use .one() instead:
Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
$(".clicker").one('click',function() {
$("#ltt").fadeIn("slow");
$('#ltt').delay(2000).fadeOut('slow');
$("#text2").delay(3000).fadeIn(1000);
$clicked = '1';
});
You declared the variable to
var clicked = '0';
but calling
$clicked = '1';
later on, so your variable will not be found.
Other than in PHP you don't need the Dollar $ to declare a variable, it's just a simple typo :)
well this should work :)
$(document).ready(function(){
$("#text2").css("display","none");
$("#ltt").css("display","none");
window.clicked = false;
$(".clicker").click(function() {
if(!window.clicked){
$("#ltt").fadeIn("slow");
$('#ltt').delay(2000).fadeOut('slow');
$("#text2").delay(3000).fadeIn(1000);
window.clicked = true;
}
});
});

bpopup multiple

I'm using a lightweight jQuery popup plugin called 'bPopup'. I'm using it on my website at the moment to load multiple popup windows when clicked. I was recently told that my code was inefficient as I was loading multiple popups with multiple JavaScript 'listeners', i.e.:
<script type="text/javascript">
;(function($) {
$(function() {
$('#my-button_1').bind('click', function(e) {
e.preventDefault();
$('#element_to_pop_up_32754925023').bPopup();
});
});
})(jQuery);
</script>
<script type="text/javascript">
;(function($) {
$(function() {
$('#my-button_2').bind('click', function(e) {
e.preventDefault();
$('#element_to_pop_up_95031153149').bPopup();
});
});
})(jQuery);
^^ The multiple JavaScript 'listeners'. And, for the Popups:
<!-- Button that triggers the popup -->
<a class="main" id="my-button_1" href="#">Popup 1</a></b><br />
<!-- Element to pop up -->
<div id="element_to_pop_up_1">
// ...
</div>
<!-- Button that triggers the popup -->
<a class="main" id="my-button_1" href="#">Popup 1</a></b><br />
<!-- Element to pop up -->
<div id="element_to_pop_up_1">
// ...
</div>
He's probably right (sure of it), but not sure how to implement this, or whether this is even possible (small chance he's wrong).
Help? And thanks!
Since you are using jquery, you should use it's on() method to attach a single listener to the parent DOM element, and use the selector parameter to properly delegate the event to it's children (the button/popups).
If this sounds confusing, a simple example might help:
HTML:
<div id="parent">
Show popup 1
<div id="popup1" class="popup">1</div>
Show popup 2
<div id="popup2" class="popup">2</div>
Show popup 3
<div id="popup3" class="popup">3</div>
Non-popup link
</div>
JS:
$('#parent').on('click', 'a.button', function (event) {
event.stopPropagation();
event.preventDefault();
var popup = $(this).attr('href');
$('#'+popup).bPopup();
});
This adds a single event listener on the parent element, which only gets triggered if the child element which triggered the event matches the selector (in this case a.button). It determines which popup to show by retreiving the popup's id from the href attribute.
You can see this example working here.
The below function ( myFunction() ) takes the Id of anchor/div tag which is clicked and another id of div content to be display. And applies the same style for all popup models. And also it hides the old popup which already opened when u open new popup. All popup properties you can change.
Here i used only for two popups but you can use it for many as same did here.
<script type="text/javascript">
function myFunction(whId,whtDivContent,e) {
//var totWidth = $(document).width();
//var marTop = position.top;
var elt = $(whId);
var position = elt.position();
var marLeft = position.left - 130;
if(marLeft <= 1) {
marLeft = 10;
}
var openModal_profile ='#openModal_profile';
var openModal_menu ='#openModal_menu';
// Prevents the default action to be triggered.
e.preventDefault();
$(whtDivContent).bPopup({
position: [marLeft, 0] //x, y
,opacity: 0.9
,closeClass : 'b-close'
,zIndex: 2
,positionStyle: 'fixed' //'fixed' or 'absolute' 'relative'
,follow: [false,false] //x, y
,onOpen: function() {
if(openModal_profile == whtDivContent) {
$(openModal_menu).bPopup().close();
}
else if(openModal_menu == whtDivContent) {
$(openModal_profile).bPopup().close();
}
$(whId).css({'background-color':"#DFDFDF"});
}
,onClose: function() { $('.close').click(); $(whId).css({'background-color':""}); }
});
}
;(function($) {
// DOM Ready
$(function() {
// From jQuery v.1.7.0 use .on() instead of .bind()
//$(id_menu).on('click',function(e) {}
var id_menu = '#id_menu';
var openModal_menu ='#openModal_menu';
$(id_menu).toggle(function(e) {
//$(id_menu).css({'background-color':"#DFDFDF"});
myFunction(id_menu,openModal_menu,e);
},function(e){
//$(id_menu).css({'background-color':""});
$('.close').click();
$(openModal_menu).bPopup().close();
});
var id_profile = '#id_profile';
var openModal_profile ='#openModal_profile';
$(id_profile).toggle(function(e) {
//$(id_profile).css({'background-color':"#DFDFDF"});
myFunction(id_profile,openModal_profile,e);
},function(e){
//$(id_profile).css({'background-color':""});
$(openModal_profile).bPopup().close();
});
//ENDS HERE
});
})(jQuery);
</script>

Hide/show DIVs in JS no longer working - potential conflict btw scripts

I used this tutorial to hid/show DIVs. Unfortunately for some reason it's no longer working (I modified a few things in my code in the meantime)... Do you see where the issue come from? jsfiddle: http://jsfiddle.net/Grek/C8B8g/
I think there's probably a conflict btw the 2 scripts below:
function showonlyone(thechosenone) {
$('.textzone').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(200);
}
else {
$(this).hide(200);
}
});
}
$('.activity-title a').click(function(){
$('.textzone').fadeOut(2000);
var region = $(this).attr('data-region');
$('#' + region).fadeIn(2000);
})​
You have a few problems going on. You're missing data-source on your <a> elements. Their "region-source" is hidden inside of the href with some function. I removed that put it into data-source and now it all works fine.
You want to do something like this:
$('.activity-title a').click(function(){
var region = $(this).attr('data-region');
$('.textzone:visible').fadeOut(2000, function () {
$('#' + region).fadeIn(2000);
});
return false; // stops href from happening
})​;
// HTML Structured like so:
<div class="source-title-box"><span class="activity-title">
Our region</span>
</div>
jsFiddle DEMO
I assume from your markup in the jsFiddle that for every link (.activity-title a), there is a .textzone. I removed the onclick event from these anchors. This way The first link corresponds with the first .textzone:
<div id="source-container">
<div id="source-region" class="textzone">
<p><span class="activity-title">Interacting with the nature</span></p>
<p>blablabla</p>
</div>
<div id="source-oursource" class="textzone">
<p><span class="activity-title">Pure, pristine, and sustainable source</span></p>
<p>blablabla</p>
</div>
<div class="source-title-box"><span class="activity-title">Our region</span></div>
<div class="source-title-box"><span class="activity-title">Our source</span></div>
</div>​
Then with the script I simply use the index of the link which is clicked to determine the appropriate .textzone to show:
var textZones = $(".textzone");
var anchors = $('.activity-title a').click(function(e){
e.preventDefault();
var index = anchors.index(this);
textZones.filter(":visible").fadeOut(2000, null, function() {
textZones.eq(index).fadeIn(2000);
});
})​

How to assign a variable using onclick of html?

I am writing a code where the onclick of html should cause a javascript variable to be assigned a value which causes a function to trigger.
<script type="text/javascript">
function set_str(numb)
{
if(numb == 1)
var str_in_func = 'a.tab_1';
else if(numb == 2)
var str_in_func = 'a.tab_2';
return str_in_func;
}
jQuery(window).bind("load", function() {
str = set_str(num);
// When a link is clicked
$(str).click(function () {
// switch all tabs off
$(".active").removeClass("active");
// switch this tab on
$(this).addClass("active");
// slide all content up
$(".content").slideUp();
// slide this content up
var content_show = $(this).attr("title");
$("#"+content_show).slideDown();
});
});
</script>
I want the javascript variable str to have a value of 'a.tab_1' when the link below is clicked
Topics
This doesn't seem to work though. The above jQuery function doesn't run at all.
There is a much easier approach to this that doesn't require all the mucking about with HTML attributes:
HTML:
<nav>
tab 1
tab 2
</nav>
<div id="content">
<section>Content 1</section>
<section>Content 2</section>
</div>
JS
$(document).ready(function() {
$('.tab').on('click', function() {
$('.active').removeClass('active');
$(this).addClass("active");
$('#content section')
.slideUp()
.eq($(this).index()).slideDown()
;
});
});
See demonstration here.
Topics
The problem is the var before your variable's name. Remove it and you will be fine. var tells javascript that you are declaring a variable for the local scope, not the context of the window, making it unavailable outside of the current context.
You want:
Topics

jquery carousel with hover effects

Here's the URL: http://174.120.239.48/~peakperf/
Here's the jQuery:
http://pastebin.com/fB16ahcZ
Site is still under heavy development.
If you mouse over "Services retention" on the carousel you will see what the function should work like. on hover a span element is faded in, on mouse out it hides. Some are stuck, some work fine. Also notice that when you click the right arrow and scroll through the carousel the spans get stuck "on".
Any help would be appreciated, thank you!
Your mark up is invalid as it is missing a closing "a" tag (see below)
</a>
Here is the error in your code.
<a href="#" id="homeslide6-show">
<img src="http://174.120.239.48/~peakperf/wp-content/themes/strausberg/images/home_service_retention.jpg" width="200" height="92" />
</li>
</ul>
Additionally your jquery code could be reduced by about 90% by using the each() function.
For example add a id to your ul and do it like so
<ul id="mycarousel">
jQuery('#mycarousel').find('span').each(function(){
jQuery(this).hover(function() {
jQuery(this).next().fadeIn('slow');
return false;
}, function(){
jQuery(this).next().fadeOut('slow');
return false;
});
});
Ps, this code is fixed to the current html structure, you should use classes for making it more flexible
You seem to have several tags with the same ID, which is not allowed. The ID is "homeslide6-show". You should also try stopping the animation, before starting and simplify your JavaScript to:
jQuery(document).ready(function() {
// hides the slickbox as soon as the DOM is ready
jQuery('#homeslide1, #homeslide2, #homeslide3, #homeslide4, #homeslide5, #homeslide6').hide();
// shows the slickbox on clicking the noted link Â
for (var i = 1; i <= 6; i++) {
jQuery('#homeslide' + i + '-show').parent().hover(
function(e, i) {
jQuery('#homeslide' + i).stop(true, true).fadeIn('slow');
e.preventDefault();
return false;
},
function(e, i){
jQuery('#homeslide' + i).stop(true, true).fadeOut('slow');
e.preventDefault();
return false;
}
);
}
});
and let me know if this works.
EDITED
My javascript above is incorrect. The following works:
jQuery(document).ready(function() {
// hides the slickbox as soon as the DOM is ready
jQuery('#homeslide1, #homeslide2, #homeslide3, #homeslide4, #homeslide5, #homeslide6').hide();
// shows the slickbox on clicking the noted link Â
for (var i = 1; i <= 6; i++) {
jQuery('#homeslide' + i + '-show').parent().data({element: '#homeslide' + i}).hover(
function() {
var element = jQuery('element');
jQuery(element).stop(true, true).fadeIn('slow');
return false;
},
function(){
var element = jQuery('element');
jQuery(element).stop(true, true).fadeOut('slow');
return false;
}
);
}
});

Categories