How to get "onclick" after click on div in link? - javascript

How to get "onclick" after click on div in link on jquery?
<a href="#">
<img src="some.jpg" />
<div class="cont" onclick="showDiv()"></div>
</a>
img {
position: relative;
}
.cont {
position: absolute;
top: 0px;
right: 0px;
}
I want that when you click on region ".cont"occurred an event that I can handle. I tried this:
$(document).ready(function() {
function showDiv() {
alert("test");
}
});
my js
$('#tmp').justifiedGallery({
rowHeight: 350,
maxRowHeight: '100%'
}).on('jg.complete', function () {
$(this).find('a').colorbox({
maxWidth : '90%',
maxHeight : '90%',
opacity : 0.2,
transition : 'elastic',
current : ''
});
});

You defined the showDiv() function within the the document.ready handler, so it is out of scope of the onclick attribute. You need to define the function at the lower level:
<head>
<script type="text/javascript">
function showDiv() {
alert("test");
}
$(document).ready(function() {
// jquery code here...
});
</script>
</head>
A better solution entirely would be to use Javascript to attach your events, as it is a better separation of concerns and removes the outdated onclick attribute:
<a href="#">
<img src="some.jpg" />
<div class="cont"></div>
</a>
$(document).ready(function() {
$('.cont').click(function() {
alert('test');
});
});

You cant write a function like this in $(document).ready(function()
try this
$(document).ready(function(){
$(".cont").click(function(){
alert("test");
});
});
or
$(document).ready(function(){
showDiv();
});
function showDiv() {
alert("test");
}

There are two ways to do this.
The way I'd do this:
$('.cont').on('click', function(){
alert('qwerty');
});
That way you wouldn't need the onclick="showDiv()" in your HTML which would make your HTML cleaner.
The way that uses you onclick of the element:
function showDiv(){
alert('zxcvb');
}
Sample at CodePen

Related

Why is my if/else JS statement using jQuery not working?

I was playing around with the code from the w3schools editor which illustrates a jQuery animate function.
I want to try and make this movement reversible though, so I added an if/else statement to allow the div to move back if it had already been clicked.
Here is my code for between the script tags:
var clicked = false;
$(document).ready(function(){
$("button").click(function(){
if (clicked == false){
$("div").animate({
left: amount,
opacity: '0.5',
height: '150px',
width: '150px'
});
clicked = true;
} else {
$("div").animate({
right: amount,
opacity: '0.5',
height: '150px',
width: '150px'
});
clicked = false;
}
});
});
I am aware there is probably a better way of doing this, but I am fairly new to jQuery. In any case seeing as jQuery is just extended JavaScript it seems strange that this doesn't work.
--- update: corrected amount not being set and included full page code ---
Here is my new code. The div still doesn't move back when clicked again.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var clicked = false;
$(document).ready(function(){
$("button").click(function(){
if (clicked == false){
$("div").animate({
left: '250px'
});
clicked = true;
} else {
$("div").animate({
right: '250px'
});
clicked = false;
}
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
It's failing because you're not setting amount!
var clicked = false;
var amount = 0;
$(document).ready(function(){
//more code that calls `amount`
})
Check this JSFiddle to see it in action: http://jsfiddle.net/1xt58q0a/1/
New JSFIddle to match updated question: http://jsfiddle.net/1xt58q0a/5/
You can use the .toggle() function.
$(document).ready(function(){
$("button").toggle(
function(){
$("div").animate({
left: amount,
opacity: '0.5',
height: '150px',
width: '150px'
});
},
function(){
$("div").animate({
right: amount,
opacity: '0.5',
height: '150px',
width: '150px'
});
}
);
});
I assume you have set amount to a value in advance.
The div doesn't change because the opacity, height and width are set the same in both options.
Embarrassing, but my mistake was a misunderstanding of CSS, not JS.
Here is the corrected - and functioning - code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var clicked = false;
$(document).ready(function(){
$("button").click(function(){
if (clicked == false){
$("div").animate({
marginLeft: '250px'
});
clicked = true;
} else {
$("div").animate({
marginLeft: '0px'
});
clicked = false;
}
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>

Why Div is not visible on button click

in my webpage i set visibility of a div hidden and i want to show it on button click,so i am writing a jquery code for it.
but some how it is not working
my asp code is
<asp:Button ID="btnGenerate" CssClass="button" runat="server" Text="Generate" OnClick="btnGenerate_Click" />
<div id="print" style="width: 80%; margin-left: 10%; margin-top: 20px;visibility:hidden;">
<input type="button" id="btnPrint" class="button" value="Print" onclick="printDiv('ReportDiv')"/>
</div>
and my jquery code for it is:
<script>
$(document).ready(function () {
$("#btnGenerate").click(function () {
$("#print").css("visibility", "visible");
});
});
</script>
please help me to fix this issue.
Thanks
Because you gave a wrong ID, Look at your html <div id="print" ...
$(document).ready(function () {
$("#btnGenerate").click(function () {
$("#print").css("visibility", "visible");
});
});
try it
<script>
$(document).ready(function () {
$("#<%= btnGenerate.ClientID %>").click(function () {
$("#print").css("visibility", "visible");
});
});
</script>
you can not get asp.net button click in jquery using $("#btnGenerate") if you want to use asp.net button in jquery then you will have to use like this $("#<%= btnGenerate.ClientID %>")
child element will not be visible until his parent element is visible. So you need to show parent div.
Here parent div #print is hidden and you are trying to show its child div #btnPrint you have to make parent div #print visible.
try this:
$(document).ready(function () {
$("#btnGenerate").click(function () {
$("#print").css("visibility", "visible");
});
});
Because .net will change the id while rendering, being runat server. You should use class for that
$(document).ready(function () {
$(".button").click(function () {
$("#print").css("visibility", "visible");
});
});

jquery zoom in and zoom out on clicking an image

I have an image which has to behave the following way:
When a user clicks on it the first time it the image should zoom-in and when clicked on the image again it should zoom-out.
Please help in figuring out how the two actions be performed by clicking on the image using jquery? Below is the code I have written for zooming in the image.
$('.tab1').click(function()
{
$(".GraphHolder").hide("slow");
$("#top-button-container").hide("slow");
$(".print").append('<button type="button">PRINT</button>');
$(this).animate({width: "70%"}, 'slow');
});
HTML:
<img id="pic" src="https://www.google.com//images/icons/product/chrome-48.png">
Jquery:
$(function(){
$('#pic').toggle(
function() { $(this).animate({width: "100%"}, 500)},
function() { $(this).animate({width: "50px"}, 500); }
);
});
Example at: http://jsfiddle.net/K9ASw/32/
Have you tried using toggleClass? You can use the optional [duration] parameter to specify how long you want the transition to take.
If really old or crappy browsers are'nt an issue, I'd go for CSS transitions, easier and smoother.
FIDDLE
**here is the script**
<script src="Script/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#Img1, #Img2, #Img3').mouseover(function () {
$(this).animate({ width: "122px", height: "110px" }, 100);
});
$('#Img1, #Img2, #Img3').mouseout(function () {
$(this).animate({ width: "118px", height: "106px" }, 100);
});
});
</script>
**Aspx code**
<img src="Images/home.jpg" id="Img1" width="118" height="106" border="0">
<img src="Images/machine.jpg" id="Img2" width="118" height="106" border="0">
<img src="Images/title_Mixie.jpg" id="Img3" width="118" height="106" border="0">
$(function () {
$('.tab1').on('click', function()
{
if($(this).hasClass('zoomed')) {
$(this).removeClass('zoomed')
$(this).children('img').animate({width: "10%"}, 'slow');
}
$(this).addClass('zoomed')
$(this).children('img').animate({width: "70%"}, 'slow');
}
});
});
I removed all the code not pertaining to the image resize.
Also, if you're dealing with an image, you have to target the image tag, not the outer div.
If the image is applied to the .tab1 class as a background image then you're sol.

inserting divs with javascript

i have the following code that i was hoping would allow me to click a button and add another box to the page but inj stread it just resets the page every time i click one of the buttons
<style>
div.box
{
width: 50px;
height: 50px;
background-image: url("Images/smallBox.jpg");
}
div.largeBox
{
width: 100px;
height: 100px;
background-image: url("Images/largeBox.jpg");
}
</style>
<script type="text/javascript">
$(function () {
setupDragging();
});
function setupDragging() {
$(".box").draggable({ snap: true });
$(".largeBox").draggable({ snap: true });
}
function addSmallBox() {
var boxArea = document.getElementById('boxArea');
var newBox = document.createElement('div');
newBox.setAttribute('class', 'box');
boxArea.appendChild(newBox);
setupDragging();
}
function addLargeBox() {
var boxArea = document.getElementById('boxArea');
var newBox = document.createElement('div');
newBox.setAttribute('class', 'largeBox');
boxArea.appendChild(newBox);
setupDragging();
}
</script>
<form>
<button onclick="addSmallBox();">small box</button>
<button onclick="addLargeBox();">large box</button>
</form>
<div id="boxArea">
</div>
please can somebody let me know what i am doing wrong and how i can achieve what i want.
ANSWER:
just an update on the final result
<style>
div.box
{
width: 50px;
height: 50px;
background-image: url("../Images/smallBox.jpg");
position: absolute;
}
div.largeBox
{
width: 100px;
height: 100px;
background-image: url("../Images/largeBox.jpg");
position: absolute;
}
</style>
<script type="text/javascript">
$(function () {
setupDragging();
$('.addBox').click(function(e){
if($(this).hasClass('smallBox')) addSmallBox();
else if($(this).hasClass('largeBox')) addLargeBox();
e.preventDefault();
})
});
function setupDragging() {
$(".box").draggable({ snap: true });
$(".largeBox").draggable({ snap: true });
}
function addSmallBox() {
$('<div>', { class: 'box' }).appendTo('#boxArea')
setupDragging();
}
function addLargeBox() {
$('<div>', { class: 'largeBox' }).appendTo('#boxArea')
setupDragging();
}
</script>
<form>
<button class='addBox smallBox'>small box</button>
<button class='addBox largeBox'>large box</button>
</form>
<div id="boxArea">
</div>
i made use of several of the answers below and this was the final result but went down the html5 route in the end.
First of all, since you are using jQuery, if I were you, I would not use the onclick attribute in your button. Instead, add an event listener like so:
$('button').click(function(){
addLargeBox();
return false;
});
OR
$('button').click(function(e){
addLargeBox();
e.preventDefault();
});
Both of which will prevent the user's browser from following the link but will execute the JavaScript as you want.
Also, since you require two different functions to be executed depending on which button is clicked, you should probably add a class or id to differentiate the two.
Your markup would then look like this:
<button class="add-box">small box</button>
<button class="add-box large-box">large box</button>
And your JavaScript would be:
$('.add-box').click(function(){
if ($(this).hasClass('large-box')) addLargeBox();
else addSmallBox();
return false;
});
The button tag you are using is a HTML5 version of a form submit button which causes a page refresh.
Change the buttons to:
<input type="button" onclick="addSmallBox();" value="small box" />
Or put return false at the bottom of each of your javascript functions.
Couple of things:
Always separate JS from code (that means lose the onclick attributes and bind them in javascript instead.)
The form is still being submitted; have your functions return false/preventDefault (jQuery) to avoid this.
Some hints:
Since you're already using jQuery, why not build html elements with it? ($('<div>',{class:'box'}).appendTo('#boxArea') for instance)
You have to return false from the click event to prevent the default browser behavior of following the link.
I'm not sure why just by glancing at the code, but perhaps you could try retrieving the boxArea.InnerHTML, appending the appropriate HTML string to it, and setting the boxArea.InnerHTML to the result.
Something like:
boxArea.InnerHTML = boxArea.InnerHTML + "<div class='largeBox'></div>";

Simple jQuery animation not working

can anyone help me fix this, what am I missing?
<script type="text/javascript">
$('#loginButton').click(function() {
$('#toplogin').animate({
height: '0px'
});
});
</script>
The onClick doesn't even execute!
The div I want the onClick event to work on is here:
<div id="loginButton">Login ยป</div>
The div I want the animation to affect is here:
div id="toplogin"> <!-- more stuff --> </div>
Remove the semicolon after height: '0px' to make your JavaScript valid.
<script type="text/javascript">
$('#loginButton').click(function() {
$('#toplogin').animate({ height:'0px' });
});
</script>
However, unless you have overflow:hidden set for #toplogin the element will still be visible, even though it's height is 0px. An easier way is just using slideUp().
<script type="text/javascript">
$('#loginButton').click(function(){ $('#toplogin').slideUp(); });
</script>
try this:
$('#loginButton').click(function() {
$('#toplogin').animate({
height: 0
},
function() {
$(this).css('display', 'none');
});
});
you should wrap your code in following construction to make it valid as jQuery code:
$(document).ready(function(){
your code;
})

Categories