How to transfer a lot of variables to a function in Javascript - javascript

How can I pass many variables to a javascript function? I would like to simplify my code. It is much too long if I have to write an extra function for each variable. Any help will be appreciated. Thank You.
jQuery(document).ready(function ($) {
$('#item1').click(function () {
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000, function () {
revapi8.revcallslidewithid('item-11');;
});
});
$('#item2').click(function () {
$('html, body').animate({
scrollTop: $("#div2").offset().top
}, 2000, function () {
revapi8.revcallslidewithid('item-12');;
});
});
$('#item3').click(function () {
$('html, body').animate({
scrollTop: $("#div3").offset().top
}, 2000, function () {
revapi8.revcallslidewithid('item-13');;
});
});
});

If your elements are as provided in question. This approach will work for you.
jQuery(document).ready(function($) {
var arr = [1,2,3]; //element iterator
arr.forEach(function(item){
$('#item' + item).click(function() {
$('html, body').animate({
scrollTop: $("#div" + item).offset().top
}, 2000, function() {
revapi8.revcallslidewithid('item-1' + item);;
});
});
})
});

You can use data-* prefix cutsom attribute to persists arbitary data with element which can be accessed using .data() or Element.dataset property.
Assign a CSS class i.e. item then use Class Selector (".class") to bind event handler
HTML
<div class='item' data-related-div="#div1" data-related-item="item-11">item 1</div>
<div class='item' data-related-div="#div2" data-related-item="item-12">item 2</div>
<div class='item' data-related-div="#div3" data-related-item="item-13">item 3</div>
Script
$('.item').click(function () {
var div = $(this).data('relatedDiv');//this.dataset.relatedDiv
var item = $(this).data('relatedItem');//this.dataset.relatedItem
$('html, body').animate({
scrollTop: $(div).offset().top
}, 2000, function () {
revapi8.revcallslidewithid(item);;
});
});

You could simple use the jQuery index() method to get the clicked elements index and use the get() method to get the corresponding div element. This will of course only work if the amount of clickable elements is equal to the div elements you want to scroll to.
Here is an example.
var $body = $('html, body');
var $itemsWrap = $('#items-wrap');
var $items = $itemsWrap.find('.item');
var $divs = $('[id^="div"]');
$itemsWrap.on( 'click', function(evt) {
var index = $items.index( evt.target );
$body.animate({ scrollTop: $($divs.get(index)).offset().top }, 666);
});
html, body {
min-height: 100%;
margin: 0;
}
div[id^="div"] {
height: 100vh;
background: tomato;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="items-wrap">
<button class="item">item-1</button>
<button class="item">item-2</button>
<button class="item">item-3</button>
</div>
<div id="div1"><h1>Div 1</h1></div>
<div id="div2"><h1>Div 2</h1></div>
<div id="div3"><h1>Div 3</h1></div>

Related

How to use multiple elements in one set of code for javascript

$(document).ready(function() {
$(".button1").click(function() {
$("html, body").animate({
scrollTop : $("#screen1").offset().top
}, 800);
});
})
$(document).ready(function() {
$(".button2").click(function() {
$("html, body").animate({
scrollTop : $("#screen2").offset().top
}, 800);
});
})
...and so on
I wrote above code in javascript. If button is clicked, it scrolls to #screen position. However, I have several ".button"s and "#screen"s that basically has the same function. I don't want to repeat the same code so I've tried for in statement, but couldn't get it right. In what way can I avoid repeating codes in this situation?
Now, I cant see your HTML code, but my suggestion would be to add the event listener to a parent element to all the buttons and then add info about the button on the button itself. Here I'm using the attribute data-screen to hold info about the "screen".
UPDATE
I refined the jquery a bit. Using on() instead of click() so that I could remove the original if statement. When the event listener is on the parent element more buttons can be added dynamically and they will work as expected.
$(document).ready(function() {
$("#buttons").on("click", "button", function(e) {
var screenid = $(e.target).attr('data-screen');
$("html, body").animate({
scrollTop: $(`#screen${screenid}`).offset().top;
}, 800);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="buttons">
<button data-screen="1">Button 1</button>
<button data-screen="2">Button 2</button>
<button data-screen="3">Button 3</button>
</div>
<div>
<div id="screen1"></div>
<div id="screen2"></div>
<div id="screen3"></div>
</div>
Assuming all the buttons & screens follow the naming convention .button${number} and #screen${number}, you can do this:
const numberOfSections = 5;
$(document).ready(function() {
for (let i = 1; i <= numberOfSections ; i++) {
$(`.button${i}`).click(function() {
$("html, body").animate({
scrollTop : $(`#screen${i}`).offset().top
}, 800);
});
}
});

Animated scroll with JQuery

How is it possible to make the text I am not clickable for some reason... (check the code below) clickable?
var container = document.querySelector('.container');
var clickMe = document.querySelector('.clickMe');
clickMe.addEventListener('click', function() {
var container = document.querySelector('.container');
$([document.documentElement, document.body]).animate({
scrollTop: $(".container").offset().top
}, 1000);
});
container.addEventListener('wheel', function() {
var scrollY = window.scrollY;
if (scrollY == 0) {
$([document.documentElement, document.body]).animate({
scrollTop: $(".nextContainer").offset().top
}, 800);
}
});
.container {
background: green;
height: 100vh;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<p class="clickMe">'wheel'</p>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div class="nextContainer">
<p class="clickMe">I am not clickable for some reason...</p>
</div>
As you see, the Wheel-listener works perfectly, while the click-listener does not. How do I solve this problem, if possible?
Thanks in advance.
The problem appear because you get only first clickable element here :
var clickMe = document.querySelector('.clickMe');
So, you attach the click event just at first element "wheel" text.
The solution to fix this problem is to get all ".clickMe" elements with querySelectorAll and attach click event to each element.
var clickMe = document.querySelectorAll('.clickMe');
clickMe[0].addEventListener('click', function() {
var container = document.querySelector('.container');
$([document.documentElement, document.body]).animate({
scrollTop: $(container).offset().top
}, 1000);
});
clickMe[1].addEventListener('click', function() {
var container = document.querySelector('.container');
$([document.documentElement, document.body]).animate({
scrollTop: $(container).offset().top
}, 1000);
});
Are you sure it's not clickable. In function which handle paragraph click add console.log("CLICKED"); and see in console if anything appears when you click. And in css add style for clickMe cursor:pointer; so when you hover it looks better.
Finally figured out the problem.
After the animation,
$([document.documentElement, document.body]).animate({
scrollTop: $(".nextContainer").offset().top
}, 800);
I needed to add JQuery:s stop() function,
$('html, body').stop();
Credits: Stop ScrollTop function when user scrolls jquery
Instead of document.querySelector('.clickMe') you can use the jQuery Selector $('.clickMe').
Than it works fine.
var container = document.querySelector('.container');
var clickMe = document.querySelector('.clickMe');
console.log(clickMe);
$('.clickMe').on('click', function() {
console.log('clicked');
var container = document.querySelector('.container');
$([document.documentElement, document.body]).animate({
scrollTop: $(".container").offset().top
}, 1000);
});
container.addEventListener('wheel', function() {
var scrollY = window.scrollY;
if (scrollY == 0) {
$([document.documentElement, document.body]).animate({
scrollTop: $(".nextContainer").offset().top
}, 800);
}
});
.container {
background: green;
height: 100vh;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<p class="clickMe">'wheel'</p>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div class="nextContainer">
<p class="clickMe">I am not clickable for some reason...</p>
</div>

How to move the page up each time to a div

I am creating a form where i have many child forms to submit,so i have used a jQuery functionality where each submit a msg will show at the top of the page ,now what i want,on each submit the page will scroll up to the div where that jQuery is calling .Here is my code
var url = "<%=addPersonalDetailsURL%>";
var type = "addPersonalDetails";
if(!($('#<portlet:namespace/>address1').val()=='' || $('#country').val()=='None' ||$('#<portlet:namespace/>primaryPhone').val()=='')){
jQuery.getJSON(url+"&address1="+address1+"&address2="+address2+"&country="+country+"&state="+state+"&city="+city+"&zip="+zip+"&skypeId="+skypeId+"&twitter="+twitter+"&primaryPhone="+primaryPhone+"&secondaryPhone="+secondaryPhone+"&type="+type, function(data) {
$('html, body').animate({
scrollTop: $(".success").offset().top
}, 800);
for(var z=0; z<data.applicationArray.length;z++){
applicationArray = data.applicationArray[z].split("$$##$$##");
address1 = applicationArray[0];
address2 = applicationArray[1];
city = applicationArray[2];
primaryPhone = applicationArray[3];
}
jQuery.getJSON is giving some result where on the basis i have to use that functionality.So can you tell how i should modify your solution
You should need to get your element's top position in the page and move the scroll to that position. Something like the code below:
jQuery(window).scrollTop(jQuery(".success").offset().top);
Note that the code above will move to the first .success position. If you have to reference a specific one, add the index in the selector, for example:
jQuery(window).scrollTop(jQuery(".success:eq(1)").offset().top);
You can do that with this function:
$("button").click(function () {
$('html, body').animate({
scrollTop: $(".whichElement").offset().top
}, 800);
});
Explanation:
If the button is clicked, we scroll the page to the element with class
whichElement and the duration of the scroll is 800ms.
Example:
$(".first-hey").click(function () {
$('html, body').animate({
scrollTop: $(".second-hey").offset().top
}, 800);
});
$(".second-hey").click(function () {
$('html, body').animate({
scrollTop: $(".third-hey").offset().top
}, 800);
});
$(".third-hey").click(function () {
$('html, body').animate({
scrollTop: $(".first-hey").offset().top
}, 800);
});
.divide {
height: 1300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="first-hey">First hey</button>
<div class="divide"></div>
<button class="second-hey">Second hey</button>
<div class="divide"></div>
<button class="third-hey">Third hey</button>

How do I make a loop in jQuery so that theres a number added to the end of my divs?

I want the numbers in the div id's and div classes to loop and be from 0 to however many divs I have.. How can I accomplish this? I've tried to put it in a for loop but it doesn't work for some reason..
$("#bokautbildning0").hide();
$(".boka_btn0").click(function(){
$("#bokautbildning0").slideToggle();
var scrollToId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(scrollToId).offset().top - 270
}, 500);
return false;
});
$("#bokautbildning1").hide();
$(".boka_btn1").click(function(){
$("#bokautbildning1").slideToggle();
var scrollToId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(scrollToId).offset().top - 270
}, 500);
return false;
});
$("#bokautbildning2").hide();
$(".boka_btn2").click(function(){
$("#bokautbildning2").slideToggle();
var scrollToId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(scrollToId).offset().top - 270
}, 500);
return false;
});
Here's the code with the loop I tried:
for ( var i = 0; i < 5; i++ ) {
$("#bokautbildning" + i).hide();
$(".boka_btn" + i).click(function(){
$("#bokautbildning" + i).slideToggle();
var scrollToId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(scrollToId).offset().top - 270
}, 500);
return false;
});
}
This answer was written for an older version of the question and is no longer correct.
The best solution would be to add a class to all those elements and use that instead of ids to run jQuery on. Let jQuery do the work to iterate over all those elements.
For example, give all elements #bokautbildningn the class .bokautbildning and change your javascript code to this:
$('.bokautbildning').hide();
$('.boka_btn1').click(function(){
$('.bokautbildning').slideToggle();
var scrollToId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(scrollToId).offset().top - 270
}, 500);
return false;
});
The jQuery for this would be pretty straightforward if you made use of data attributes. To wit:
Html example:
<div data-number="1"></div>
<div data-number="2"></div>
<div data-number="3"></div>
<div data-number="4"></div>
<div data-number="5"></div>
jquery:
$("div[data-number]").each(function() {
var number = $(this).data("number");
$(this).html(number);
alert(number);
})
To see it in action:
http://jsfiddle.net/uubxj55r/
You need to use Each and just make sure all items have the same class within each section. There is no need to use the numbering system that you are currently using.
$('.MyDivs').each(function(index){ //Loop through all the elements with class of 'MyDivs'
var thisElement = $(this); //get the current element we're on in the loop
thisElement.find('.bokautbildning').slideToggle(); //Find the element with class 'bokautbildning' within the current element in the loop and slideToggle it
thisElement.find('.boka_btn').click(function() { //Find the element with classs 'boka_btn' within the current element in the loop and add a click listener
//Code for click event happens here
});
}
Here's an example: http://jsfiddle.net/o85tk0s3/

JQuery rolling - stop previous & generalize

i have code like this:
JavaScript
$( document ).ready(function() {
$("a.link1").click(function (){
//$(this).stop().preventDefault().animate(function(){
$('html, body').animate({
scrollTop: $("#link1").offset().top
}, 2000);
//});
});
$("a.link2").click(function (){
//$(this).stop().preventDefault().animate(function(){
$('html, body').animate({
scrollTop: $("#link2").offset().top
}, 2000);
//});
});
$("a.link3").click(function (){
//$(this).stop().preventDefault().animate(function(){
$('html, body').animate({
scrollTop: $("#link3").offset().top
}, 2000);
//});
});
});
Body of HTML:
<div id="menu">
LINK 1
LINK 2
LINK 3
</div>
<div id="content">
<a name="link1" id="link1"></a>
<!--some text-->
<a name="link2" id="link2"></a>
<!--some text-->
<a name="link3" id="link3"></a>
<!--some text-->
</div>
Please help me with this:
Stop doesn't seem to work the way I wanted. I want to somehow stop previous rolling when another link is activated.
Is there any way of generalization of the jQuery part. I have more than 3 menu links and I don't want to make a special function for each.
Thank you very much for your help.
Gomi
You can generalize by extracting the click callbacks to a common function:
var linkClickCallback = function(selector){
$('html, body').stop().animate({
scrollTop: $(selector).offset().top
}, 2000);
}
$( document ).ready(function() {
$("a.link1").click(linkClickCallback.bind(null, '#link1'));
$("a.link2").click(linkClickCallback.bind(null, '#link2'));
$("a.link3").click(linkClickCallback.bind(null, '#link3'));
});
Note that in the linkClickCallback i also wrote the proper use of stop() method.
EDIT:
This will work for all items in menu:
$( document ).ready(function() {
$("#menu a").click(function(e){
e.preventDefault();
linkClickCallback('#' + this.className);
});
});
with the same linkClickCallback function.
Yeah just generalise a function like this and then inside the function, look for the caller (this):
$("#menu a").click(function(e){
var t = $(this)
$('html, body').animate({
scrollTop: t.offset().top
}, 2000);
});

Categories