jQuery activate .click() only when clicking specified element - javascript

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();
});
});

Related

How to separate javascript so it is not inline but as a separate snippet

I have some code that works perfectly within the html editor within WordPress. The problem is that when switching to the visual editor it strips out the javascript. I am a novice when it comes to code, and wondering if someone can help separate the javascript so I can add it as a separate script to the wordpress page.
<div class="couponactivate">
<div class="coupon1">
<h3>Subtitle</h3>
<p>This is our Standard Coupon which gives 10% off</p>
</div>
<div class="activatebutton">
<div style="position:relative;"><a onclick="jQuery('#jcorgcr-clean-jcorgcoupon-coupon1').hide()" target="_blank" href="http://www.test.com" rel="nofollow">DOJU</a>
<div onclick="window.open('http://www.test.com');jQuery('#jcorgcr-clean-jcorgcoupon-coupon1').hide()" id="jcorgcr-clean-jcorgcoupon-coupon1" class="couponrevealcoupon">REVEAL COUPON</div>
</div>
<div class="expiry">Expires 31 July 2014</div>
</div>
<div style="clear:both;"></div>
</div>
Really you should add a class or ID to .activatebutton > div > div but if you want to keep the markup unchanged:
<script>
jQuery(document).ready(function() {
jQuery('.activatebutton').on('click',function() {
jQuery('#jcorgcr-clean-jcorgcoupon-coupon1').hide();
});
jQuery('.activatebutton > div > div').on('click',function() {
window.open('http://www.test.com');
jQuery('#jcorgcr-clean-jcorgcoupon-coupon1').hide();
});
});
</script>
Essentially what you want to do is bind to onclick from outside the HTML, rather than in the element itself. So instead of this:
<a onclick="jQuery('#jcorgcr-clean-jcorgcoupon-coupon1').hide()" target="_blank" href="http://www.test.com" rel="nofollow">DOJU</a>
You might have something like this:
<a id="someLink" target="_blank" href="http://www.test.com" rel="nofollow">DOJU</a>
<script type="text/javascript">
jQuery('#someLink').click(function () {
jQuery('#jcorgcr-clean-jcorgcoupon-coupon1').hide();
});
</script>
That script block can be put elsewhere on the page, or the script can be put into a separate file and a script block can just reference that file.
Note that this is a very simplified example just to demonstrate the idea of binding to an element's event from outside the element. There are lots of things to consider, and I imagine you'll find those things and learn them with practice. For example, since the page is parsed in order then that script will need to be placed after the link tag in order for it to work. If it's before the link tag, then you'd need to wrap it in the document's ready event to wait for the tags to load before trying to bind to their events. Something like this:
<script type="text/javascript">
jQuery(function () {
jQuery('#someLink').click(function () {
jQuery('#jcorgcr-clean-jcorgcoupon-coupon1').hide();
});
});
</script>
<a id="someLink" target="_blank" href="http://www.test.com" rel="nofollow">DOJU</a>
If tags change over time (such as being added/removed dynamically) then there would be even more to consider in terms of binding to their events. But at its simplest, using jQuery (since you're already using it), you just identify the element and use something like the click() function on that jQuery-identified element (or set of elements) to bind to that event.
Since you are new and the question is easy I will help you. Next time you have to try first.
myscript.js:
jQuery(function() {
jQuery(".activatebutton a").on("click", function() {
jQuery('#jcorgcr-clean-jcorgcoupon-coupon1').hide();
});
jQuery("#jcorgcr-clean-jcorgcoupon-coupon1").on("click", function() {
window.open('http://www.test.com');
jQuery('#jcorgcr-clean-jcorgcoupon-coupon1').hide();
});
}
put this in head tag (after jquery):
<script type="text/javascript" src="myscript.js"></script>
the rest of html:
<div class="couponactivate"><div class="coupon1">
<h3>Subtitle</h3>
<p>This is our Standard Coupon which gives 10% off</p>
</div><div class="activatebutton"><div style="position:relative;"><a target="_blank" href="http://www.test.com" rel="nofollow">DOJU</a><div id="jcorgcr-clean-jcorgcoupon-coupon1" class="couponrevealcoupon" >REVEAL COUPON</div></div>
<div class="expiry">Expires 31 July 2014</div>
</div><div style="clear:both;"></div></div>
Hope this helps you
<!DOCTYPE html>
<html >
<head>
<script type="text/javascript" src="globe/script/jquery.js"></script>
<title>
Html5 All in One
</title>
</head>
<body >
<div class="couponactivate">
<div class="coupon1">
<h3>Subtitle</h3>
<p>This is our Standard Coupon which gives 10% off</p>
</div>
<div class="activatebutton">
<div style="position:relative;"><a target="_blank" href="http://www.test.com" rel="nofollow">DOJU</a>
<div id="jcorgcr-clean-jcorgcoupon-coupon1" class="couponrevealcoupon">REVEAL COUPON</div>
</div>
<div class="expiry">Expires 31 July 2014</div>
</div>
<div style="clear:both;"></div>
</div>
<script>
$(document).ready(function()
{
$(".activatebutton a").click(function(){
jQuery('#jcorgcr-clean-jcorgcoupon-coupon1').hide()
})
$("#jcorgcr-clean-jcorgcoupon-coupon1").click(function(){
window.open('http://www.test.com');jQuery('#jcorgcr-clean-jcorgcoupon-coupon1').hide()
})
})
</script>
</body>
</html>

How do I pass variables to a jQuery function?

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>

Jquery - using "this" to dynamically show and hide

<div class="show_hide panel-header" rel="#panel">
<h4>Disclaimer</h4>
</div>
<div id="panel" class="panel">
<p>Lorem ipsum</p>
</div>
Above is my HTML ... a simple div for the header (event handler) and the hidden div to show/hide. Works perfectly for a simple show/hide, but I may have several panels on screen at once and I don't want to explicitly ID each one and give it it's own function. How can I use the this selector to achieve dynamic interactions?
My JQuery currently:
<script type="text/javascript">
$(document).ready(function(){
$(".panel").hide();
$(".show_hide").show(); //Probably don't need this line...
$('.show_hide').click(function(){
$(this).children("div").slideToggle();
});
});
</script>
Any help is appreciated. I'm new to JS/JQuery and having some trouble understanding the different selectors. Thanks!
Your div isn't a child, it's the next div in line:
$(this).next("div.panel").slideToggle();
you can try this
<script type="text/javascript">
$(document).ready(function(){
$(".panel").hide();
$('.show_hide').click(function(){
$(this).next(".panel").slideToggle();
});
});
</script>

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();

show() div problem

I am an absolute beginner in this field. I have written the following code but it's not working. Can someone explain where is the error?
<script type="text/javascript">
$("button").click(function(){
$("div").show("slow");
});
</script>
<button>show</button>
<div style="min-height:300px; min-width:400px; border:10px solid grey; display:none;"></div>
this is a link
You execute the jQuery before the button is there. So at the point jQuery is executed, the button is not existent.
The solution is to use $(document).ready(...).
All elements on a page (HTML) are parsed to the DOM of that page. The DOM is a hierarchical collection of all elements. You can select elements out of it using jQuery.
However, obviously the DOM needs to be fully there before you can select the elements. In your case, you first select the button, and create it afterwards. That does not work. At the time of the selector the button does not exist yet.
Using jQuery's $(document).ready(), you can defer the function containing selectors until the DOM is fully loaded and parsed - at which time the selector works because the elements are there.
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function(){
$("div").show("slow");
});
});
</script>
<button>show</button>
<div style= "min-height:300px; min-width:400px; border:10px solid grey; display:none;"></div>
this is a link
You may be trying to listen for the click event before the button exists. Try waiting for the page contents to load:
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function(){
$("div").show("slow");
});
});
</script>
<button>show</button>
<div style= "min-height:300px; min-width:400px; border:10px solid grey; display:none;"></div>
this is a link
As you can see from the fiddle here http://jsfiddle.net/bQUFE/ your code works (the div is shown when you click)
If you don't have this result always check:
1)that you loaded jquery before your script
2)Always use $(document).ready() like this:
$(document).ready(function(){
$("button").click(function(){
$("div").show("slow");
});
});
the javascript is executed before the document has loaded, so the click-handler can't be attached to the button. to avoid this, wrap your code into a domready-function like this:
$(document).ready(function() {
$("button").click(function(){
$("div").show("slow");
});
}
It probably is working but as your <div></div> is empty you might notice it.
Also make sure you only run your JQuery script AFTER the div has been added to your HTML.
May I also suggest to use better identifiers, because you might eventually have many div's and buttons on your page.
Example:
<button id="btn1">Click me</button>
<div id="hidden_div" style="display: none">
Hello there!
</div>
<script type="text/javascript">
$('button#btn1').click(function() {
$('div#hidden_div').show('slow');
});
</script>
You code runs before the button is created so it cannot bind the event.
So you need to put your code in the document.ready event. In jQuery this is handled by $(document).ready(handler) or $(handler).
Documentation at http://api.jquery.com/ready/
Fix to your code to make it work
$(function(){
$("button").click(function(){
$("div").show("slow");
});
});
demo at http://jsfiddle.net/gaby/vkrzt/
you need to give your elements "id"
so:
<button id="mybutton"></button>
and
<div id="mydiv"></div>
Then you'll use $("#mybutton") or $("#mydiv") to call these

Categories

Resources