How do I pass variables to a jQuery function? - javascript

I would like to make a form where the you could hide (toggle) unnecessary lines using buttons (with jQuery). I have started working on a page but unless I can reuse the jQuery function I will have to write one function for every button which might be tens of times. How do I pass a variable to the function so that I can use the same function for all buttons?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
$("#para1").toggle();
});
});
</script>
<script>
$(document).ready(function(){
$("#button2").click(function(){
$("#para2").toggle();
});
});
</script>
</head>
<body>
<button id="button1">Meat</button><br>
<div id="para1">Meat<br>
More meat</div>
<button id="button2">Bread</button><br>
<div id="para2">Bread<br>
More bread</div>
</body>
</html>

If you control the HTML (which it looks like you do), there are lots of ways to solve this. The general answer to your question is that you don't to pass info to the event handler. You can use the this value in the event handler that points to the clicked-on button to then figure out which para to operate on for that given click.
One option would be to add a data attribute to the button that tells it which div to toggle and then, in the click handler, fetch the data attribute from the clicked on button and toggle that item.
Data Attribute
<button class="buttonToggle" data-para="para1">Meat</button><br>
<div id="para1">Meat<br>
More meat</div>
<button class="buttonToggle" data-para="para2">Bread</button><br>
<div id="para2">Bread<br>
More bread</div>
<script>
$(document).ready(function(){
$(".buttonToggle").click(function(){
var id = $(this).data("para");
$("#" + id).toggle();
});
});
</script>
Common Container
You could also put both in a common container and use only class names like this:
<div class="toggleContainer">
<button class="buttonToggle">Meat</button><br>
<div class="foodItem">Meat<br>
More meat</div>
</div>
<div class="toggleContainer">
<button class="buttonToggle">Bread</button><br>
<div class="foodItem">Bread<br>
More bread</div>
</div>
<script>
$(document).ready(function(){
$(".buttonToggle").click(function(){
$(this).closest(".toggleContainer").find(".foodItem").toggle();
});
});
</script>
Dom Position
Or, you could keep with your current HTML and go strictly be position in the DOM:
<button id="button1">Meat</button><br>
<div id="para1">Meat<br>
More meat</div>
<button id="button2">Bread</button><br>
<div id="para2">Bread<br>
More bread</div>
<script>
$(document).ready(function(){
$("#button1, #button2").click(function(){
$(this).next().next().toggle();
});
});
</script>
Personally, I prefer the second option (with the common container) because it's very robust and uses only class names so you don't have to make ID values unique or maintain them and the code automatically works for however many of these blocks you have. As long as the two items (button and food item) stay in the container, the code doesn't have to change even if the HTML layout gets modified a bit.
The first option requires you to maintain id values. The second option requires you to keep the DOM position right between button and food item.

This example uses a custom data-hide attribute to define the element to hide.
Also notice that the click is bound to the class="button" = to every element with class button and not to the id.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$(".button").click(function(){
var elementToHide = $(this).data("hide");
$("#"+elementToHide).toggle();
});
});
</script>
</head>
<body>
<button class="button" id="button1" data-hide="para1">Meat</button>
<br>
<div id="para1">Meat<br>
More meat
</div>
<button class="button" id="button2" data-hide="para2">Bread</button>
<br>
<div id="para2">Bread<br>
More bread
</div>

Related

Javascript to Hide/Show Div using buttons, HTML is in a rich text component in AEM, can't get it to work?

I cannot get this to work.
I have 2 buttons. I also have divs.
When I click 1 button, I want 1 div to show and for the other to be hidden.
When I click the other button, I want the opposite to happen.
They should both be hidden on default.
Javascript function:
$(document).ready(function() {
$("#button-one").click(function() {
$("#div-one").hide();
$("#div-two").show();
});
});
$(document).ready(function() {
$("#button-two").click(function() {
$("#div-one").show();
$("#div-two").hide();
});
});
I have also tried $('#sdfsdfs').css('display', 'block'), and document.getElementById("fsdfsdf").style.display="block";
HTML extract:
<div class="buttonOne">
<button id="button-one" value="button one"> Button One </button>
</div>
<div class="buttonTwo">
<button id="button-two" value="button two"> Button Two </button>
</div>
<div class="divOne" id="div-one" style="display: none;">
Some HTML
</div>
<div class="divTwo" id="div-two" style="display: none;">
Some HTML
</div>
</div>
</div>
Code above is how it goes, ignore the names.
What happens is when I load the page, each div is set to display: none, which is fine, however the clicks do not change the display to show. I am editing the values of a rich text component in AEM as well if that changes anything.
I have 2 buttons. I also have divs.
When I click 1 button, I want 1 div to show and for the other to be hidden.
When I click the other button, I want the opposite to happen.
They should both be hidden on default.
Code all is put above. Tried a lot of different ways of editing display, as well as setting the ID on css itself to display: none and editing on javascript.
you have many mistakes that you can see if you want to.
your id for your second div that you want to show is not the same in your javascript divTwo vs. div-two
another is your last div isnt closed before you close the form.
another is that you have html inside a script tag? </script> is a closing tag.
and finally, its not a big deal but you should only have 1 ready js event. i left it in for you to show you that is still does work though.
here is working version of your code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>test</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
</head>
<body>
<div class="buttonOne">
<button id="button-one" value="button one"> Button One </button>
</div>
<div class="buttonTwo">
<button id="button-two" value="button two"> Button Two </button>
</div>
<div class="divOne" id="div-one" style="display: none;">Some HTML 1</div>
<div class="divTwo" id="div-two" style="display: none;">Some HTML 2</div>
<script type="text/javascript">
$(document).ready(function() {
$("#button-one").click(function() {
$("#div-one").hide();
$("#div-two").show();
});
});
$(document).ready(function() {
$("#button-two").click(function() {
$("#div-one").show();
$("#div-two").hide();
});
});
</script>
</body>
</html>
You can use fadeIn() to show the content, it gives a nice effect
<script type="text/javascript">
$(document).ready(function() {
$("#button-one").click(function() {
$("#div-one").hide();
$("#div-two").fadeIn();
});
});
$(document).ready(function() {
$("#button-two").click(function() {
$("#div-one").fadeIn();
$("#div-two").hide();
});
});
</script>

jQuery activate .click() only when clicking specified element

I am attempting to create a cookie notification that will use .slideToggle (or slideUp/Down) to hide the element once a user has clicked "agree" (or cancel, once I add it).
Currently, the element will slideToggle when you click anywhere on the page, not just when clicking the "agree" button like I am trying to do.
I am doing this on a Wordpress.org site (I am unsure if that can affect it), and I am only just learning JavaScript/jQuery so I apologize if i am misunderstanding how .click or .slideToggle works.
The code is as follows:
<style>
.test{
display:inline-block;
background-color:#000;
color:#FFF;
text-align:center;
width:100%;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="cdn.jsdelivr.net/jquery.cookie/1.4.1/jquery.cookie.min.js"></script>
<script type="text/javascript">
var agree=function(){getElementById("#agree")};
$(agree).click(function(){
$("#box").slideToggle();
});
</script>
<div class="test" id="box">
<p>We Use Cookies</p>
<button id="agree" type="button">Agree</button>
</div>
The issue is that you attempt to wire up your event before the element exists:
<script type="text/javascript">
$("#agree").click(function(){
$("#box").slideToggle();
});
</script>
<div class="test" id="box">
<p>We Use Cookies</p>
<button id="agree" type="button">Agree</button>
</div>
You can't add an event to an element that doesn't exist yet.
You can fix this a number of ways:
1 Add code after the element exists:
<div class="test" id="box">
<p>We Use Cookies</p>
<button id="agree" type="button">Agree</button>
</div>
<script type="text/javascript">
$("#agree").click(function(){
$("#box").slideToggle();
});
</script>
2 Use document ready:
<script type="text/javascript">
$(function() {
$("#agree").click(function(){
$("#box").slideToggle();
});
});
</script>
<div class="test" id="box">
<p>We Use Cookies</p>
<button id="agree" type="button">Agree</button>
</div>
3 Use event delegation:
<script type="text/javascript">
$(document).on("click", "#agree", function(){
$("#box").slideToggle();
});
</script>
<div class="test" id="box">
<p>We Use Cookies</p>
<button id="agree" type="button">Agree</button>
</div>
the element will slideToggle when you click anywhere on the page
what's happening is that after var agree=function(){getElementById("#agree")}; then agree == null so you're doing $(null).click(... which then applies to the whole page. If you changed this to $("#agree").click(... then you'd have the issue described above (which is why you couldn't get it to work this way)
This agree function never returns anything. var agree=function(){getElementById("#agree")}; Additionally, you never call the function (only pass a reference to the function). Lastly, you should put your jquery inside the document ready event so your entire page has loaded before the script runs.
Try this javascript:
$(function() {
$("#agree").click(function(){
$("#box").slideToggle();
});
});

Copy/Clone div content to another div

I need to copy content from div1 and paste/append it to div2 by click. Then if I change content in div1 and click the button again the content should go to div3 without changing the content in div2. This is what I found so far.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="$('#div2, #div3').html($('#div1').html());">Copy</button>
<div id="div2"></div>
<div id="div3"></div>
Because I assign value it would paste the same in both divs and I have no idea how to do it separately. I guess some loops will be needed.
Is it possible and if it is could somebody give me some ideas or links to read materials. Thanks in advance!
You can use a variable to store the number of the div element and then increment it accordingly. (Here I am assuming only div2 and div3 are there)
Since you have not mentioned how the value of div1 is going to update. I am manually doing it using $('#div1').html("New Value"); inside the function add().
<html>
<body>
<body>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="add()">Copy</button>
<div id="div2"><p>div1 Placeholder</p></div>
<div id="div3"><p>div2 Placeholder</p></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var n = 2;
function add(){
$('#div'+n).html($('#div1').html());
$('#div1').html("<p>New Value</p>");
n++;
}
</script>
</body>
</html>
Try running the snippet. Clicking the button once will put the value of div1 to div2 and then it changes the original content of div1 to New Value. Again if you click the button, the new value of div1 i.e., New Value will be put to div3.
Though this will also try to update div1 again to New Value, which won't make any change. It would be better if you write some other ways to update the div1 element.
Take care of the <p> tag if you want it to be retained. Well, that also depends on the way you update the value of div1.
To append you can use $('#div'+n).append($('#div1').html());
I wrote a little help code to get you started. So what i did was to move the logic to a function which iterate a variable i (which can only take the value 2 and 3). This does not check if the text has changed and will overwrite div2 and div3 in turns on every click (remove if test if you only want to do it once).
<html>
<body>
<body>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="copyPaste()">Copy</button>
<div id="div2"></div>
<div id="div3"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
var i = 2;
function copyPaste() {
//add logic to check if text has changed before executing next line
$(`#div${i++}`).html($('#div1').html());
if(i < 3) i = 2;
}
</script>
</body>
</html>
Using a script tag with javascript code as in Saif's answer is perfectly valid (you only should be careful not to overwrite the global var used to keep count). To be more inobtrusive the click event could also be added in the script tag.
As another possibility with the opposite approach, you could do all in the the button attributes, using jQuery's data. The count is here stored in an attribute in the button, but it could also be stored in the original div #div1. The code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="$('#div' + $(this).data('targetdiv')).html($('#div1').html()); $(this).data('targetdiv', $(this).data('targetdiv') + 1);" data-targetdiv="2">Copy</button>
<div id="div2"></div>
<div id="div3"></div>
Some important notes about data: using data to change the value doesn't update the DOM attribute itself, because once the value is retreived from the attibute, jQuery uses an internal javascript code to keep the value. There's no real need to udate the DOM, but if you really want it to, you can use attr instead of data. But if you use attr, never mix it with calls to data, as the latter won't see the DOM updates after the first time it has retreived the value (because it uses the value stored in the internal javascript cache instead of reading the DOM attribute).

jQuery - Display divs one by one

I am trying to write a simple script which will be able to read/display every single DIV one by one (without interfering with the other divs inside). Unfortunately, my idea didn't work as I thought it will. I achieved what I aimed for with .children().remove().each but found out that it skips the first div and deletes all the others inside. I will be really grateful if someone can help me or point what I am doing wrong.
$(function Testing(){
$("div").each(function(){
var Div = $(this).text();
alert(Div);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="Alpha">
Alpha
<div id="Bravo">
Bravo
<div id="Charlie">
Charlie
<div id="Delta">
Delta
</div>
</div>
</div>
</div>
</body>
It looks like you want to have the nested structure. If that is the case you can do it at least a couple of ways:
$(function Testing() {
$("#container div").each(function() {
// my variation on this answer: http://stackoverflow.com/a/32170000/1544886
var Div = $(this).contents().not($(this).children()).text();
/* or another way: http://stackoverflow.com/a/33592275/1544886
var Div = $(this)
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
*/
alert(Div);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div id="Alpha">
Alpha
<div id="Bravo">
Bravo
<div id="Charlie">
Charlie
<div id="Delta">
Delta
</div>
</div>
</div>
</div>
</div>
I added div#container ONLY because I didn't like the extra alerts generated from the divs created by having a code snippet. It's not necessary to do this in your code... you can ignore it and just use your selector $("div").
To get your desired output, you need to change your HTML so that each div only contains the text that you want it to output.
You'll notice two blank alerts when running this code snippet. This is because there are additional divs placed in the code snippet by SO (hidden). These extra alerts would not show in your local script.
$(function Testing() {
$("div").each(function() {
var div_text = $(this).text();
alert(div_text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="Alpha">Alpha</div>
<div id="Bravo">Bravo</div>
<div id="Charlie">Charlie</div>
<div id="Delta">Delta</div>
</body>
Also, use descriptive variables. It is best to start this practice now (since you're learning) so you don't form bad habits. I changed Div to div_text as an example.

How to get a value from div without write some event (onclick,etc) using jquery

I have some question about how to get some value from some element like div,etc using jquery and without write onclick event or etc on the div where I want to get that value.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="test" title="test1">test</div>
<div id="test2" title="test2">test2</div>
<script>
function getVal(attr,value){
$("#show").text("this "+attr+" have value ="+value);
}
$(document).ready(function(){
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
});
</script>
<div id="show"></div>
</body>
</html>
Usually to get some value from div that i click, I add an onclick event on div like
<div id='test' onclick="getVal(test)" ></div>
and it will return "test". And the code that I write above nearly what I want, but the problem that I have is if I have a many div, how can I get the value from each div that I click just using jquery click function and I don't need to write
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
$("#test2").click(function(){
getVal("#test2",$("#test2").attr("title"));
});//and so on
here the code that I use to achieve what I want, using onclick event that I put on div:
<script type="text/javascript">
function overlay(rel){
var value = rel;
$(document).ready(function(){
$(".img"+value).click(function(){
$(".overlay-bg"+value).fadeIn();
});
$(".close"+value).click(function(){
$(".overlay-bg"+value).fadeOut();
})
});
}
</script>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-a.jpg" class="img1" onclick="overlay(1)" title="photo1" alt="photo1"/>
</div>
<div id="overlay-bg" class="overlay-bg1">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/a.jpg"/>
<span>photo1</span>
<span style="font-size:0.8em;"><p>photo a</p></span>
<div id="close" class="close1"></div>
</div>
</div>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-b.jpg" class="img2" onclick="overlay(2)" title="photo2" alt="photo2"/>
</div>
<div id="overlay-bg" class="overlay-bg2">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/b.jpg"/>
<span>photo2</span>
<span style="font-size:0.8em;"><p>photo b</p></span>
<div id="close" class="close2"></div>
</div>
</div>
I'm really want to know how to resolve my problem.
Give the elements you want to attach the click event handler to the same class. Then use the class selector [docs] to select all of them:
$('.sharedClass').click(function() {
getVal(this.id, $(this).attr("title"));
});
jQuery will bind the event handler to each of the selected elements.
There are many ways to select elements [docs], selection by ID or class are just two of them. You might also find the jQuery tutorial useful to get a better idea of how jQuery works.
you can use the this keyword within the handler function, and it will point to the element that was clicked
Here's the correct way to do it.
Put a class name to your target div e.g.
<div id="test" class="clickable" title="test">test</div>
<div id="test2" class="clickable" title="test">test</div>
...
...
Then create a jQuery event with selected class
$('.clickable').click(function(){ ... });
<div id="test">harsh</div>
<script>
alert(document.getElementById('test').innerHTML);
</script>
If you want to call this function with the click of every div, use :
$("div").click(function(){
getVal($(this),$(this).attr("title"));
});
If you want to call the function for a set of divs, but not all, give those divs a class name as suggested by #Felix Kling.
Check out the jQuery Selectors to get a better idea.
Not sure what you're trying to achieve.
If you have multiple values how do you want to store them?
If you have an array that you wanted to populate you can use the each() function on a JQuery selector to traverse all elements selected.
Like so:
var values = new Array();
$(document).ready(function(){
$('#test1, #test2').each(function(){
values.push($(this).html());
});
});
You could also store the values in an associative way to make retrieval a bit easier if you didn't want to iterate through an array. For example you could use the value of the 'title' attribute as the key in the array.
Replace the values.push() line with this line of code:
values[$(this).attr('title')] = $(this).html();

Categories

Resources