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
Related
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>
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;
}
});
});
i'm trying to get the href value in multiple links or tag a.and i tried with this code
var val;
$(document).ready(function() {
$("a").click(function() {
window.val = $(this).attr("href");
alert(window.val);
});
it is working fine for the multiple links and which is inside the file that is local, here few demo links
a
b.....
but problem is i want that href value globally available because i'm using that in other file . My problem is how to make it global, or is there any other way to do it.
and how to write our own function to work the same thing without using $(document).ready function.
this whole thing in one html page but i want only href value in other html page , so if we write our own js function we can use this in both html pages . And that function should return href. but here i dono how to return to $(document).ready function.
You can create an object-based variable:
var screen = {
link:''
};
And then assign / access on click:
$('a').on('click',function(){
screen.link = this.href;
alert(screen.link);
});
I advocate this over assigning variables to the window ... a little more control this way.
Notice I used this.href instead of $(this).attr('href'). As the most interesting man in the world says, I don't always use vanilla JS, but when I do it's about 600,000 times faster.
EDIT So you want to get rid of $(document).ready() huh? Now you're venturing into the shark-infested waters of pure vanilla JS.
var screen = {
link:'',
assignLink:function(href){
screen.link = href;
alert(href);
}
},
links = document.getElementsByTagName('a');
if(window.addEventListener){
for(i = links.length; i--;){
links[i].addEventListener('click',function(){
screen.assignLink(this.href);
});
}
} else {
for(i - links.length; i--;){
links[i].attachEvent('onclick',function(){
screen.assignLink(this.href);
});
}
}
This is just winging it, so don't scathe me if it isn't flawless, its more to make a point. See why jQuery is so handy? All that extra crap is done in the background for you, so that you just need to deal with the burden of $(document).ready() and not have to deal with the rest of this kind of stuff.
EDIT AGAIN So ... you want to access this value across pages?
var screen = {
link:((localStorage['link'] !== null) ? localSorage['link'] : ''),
setLink:function(href){
screen.link = href;
localStorage['link'] = href;
alert(href);
},
getLink:function(){
return screen.link;
}
};
$('a').on('click',function(){
screen.setLink(this.href);
});
This use of localStorage is just an example ... you can get more elaborate or use cookies if you want IE7- to work, but this just providing ideas. You can set the value whenever you want using the screen.setLink function passing the href, or you can get the value whenever you want using the screen.getLink function.
Take a look at this example:
<!DOCTYPE html>
<html>
<head>
<title>Try jQuery 1.9.1 Online</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var val;
$(document).ready(function() {
$("a").on('click', function() {
window.val = $(this).attr("href");
alert(window.val);
return false;
});
$("div").on('click', function() {
alert (val);
});
});
</script>
</head>
<body>
a
b
<div>click here</div>
</body>
</html>
Once you click either the link a or b val will be set. Clicking the div tag will alert you the current reference of val.
Declare val outside to make it global and you can use the val inside the function to set the href globally
var val;
$(document).ready(function() {
$("a").click(function(e) {
e.preventDefault();
val = $(this).attr("href");
alert(val);
});
});
jsfiddle
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>
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);
});
})