Calling a specific function alone in javascript or jquery - javascript

i have a piece of code like this.
// HTML file
<div class="box" ng-click="displayinfo()">
click here to display info about this page.
<div class="content" ng-click="displaytext()">
Click here to display text.
</div>
click here to display info about this page.
</div>
// JS file
$scope.displayinfo = function()
{
alert('info');
}
$scope.displaytext = function()
{
alert('Text');
}
the thing is while clicking on 'click here to display text', it is calling both functions and displaying 'Text' and 'info'. but i dnt want to display 'info' here. i cannot change the html div structure.
how to do that?

It's a little hidden in the docs, but if you look here: http://docs.angularjs.org/api/ng.directive:ngClick
You can see that parameters it mentions an $event object. So your html will become:
<div class="box" ng-click="displayinfo($event)">
click here to display info about this page.
<div class="content" ng-click="displaytext($event)">
Click here to display text.
</div>
click here to display info about this page.
</div>
and then your javascript will become:
$scope.displayinfo = function($event)
{
$event.stopPropagation();
alert('info');
}
$scope.displaytext = function($event)
{
$event.stopPropagation();
alert('Text');
}
jsfiddle: http://jsfiddle.net/rtCP3/32/

Instead calling functions there inline use jquery to solve this issue:
$('.box').click(function(){
displayinfo();
});
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
displaytext();
});
demo code for e.stopPropagation(): http://jsfiddle.net/HpZMA/
var a = "text for info";
$('.box').click(function(){
$(this).append(a)
});
var b = "text for info";
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
$(this).append(b)
});

For native javascript solution you need to pass event as argument to your 2 methods in order to prevent the event from propagating
<div class="box" onclick="displayinfo(event)">
Then change js to:
var displayinfo = function(event) {
event.cancelBubble = true
alert('info')
}
var displaytext = function(event) {
event.cancelBubble = true
alert('text')
}
DEMO: http://jsfiddle.net/MvgTd/

whatever you are getting.stopPropagation();
in your case
$event.stopPropagation();

Related

click function triggered from div

I have got a button wrapped inside a div.
The problem is that if I click the button, somehow the click function is triggered from the div instead of the button.
Thats the function I have for the click event:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
}
Thats my HTML (after is is created dynamically!!):
<div id="ButtonDiv">
<div class="Line1" id="Line1Software">
<button class="Line1" id="Software">Test</button>
</div>
</div>
So now myVariable from the click function is 'Line1Software' because the event is fired from the div instead of the button.
My click function hast to look like this because I am creating buttons dynamically.
Edit:
This is how I create my buttons and wrapp them inside the div
var c = $("<div class='Line1' id='Line1Software'</div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you are trying to add an event listener to the button you should probably be using $('#Software') instead of $('#ButtonDiv')
The real problem is that neither the div nor the button have an id.
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you only want it to match the innermost element, then use return false to stop the bubbling.
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
console.log(myVariable);
return false;
});
var c = $("<div class='Line1' id='Line1Software'></div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ButtonDiv">
</div>
Your question is a bit odd because you give yourself the answer... Look at your code, you are explicitly using event delegation:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
});
This code means that, for each click on a .Line1 element, the event will be delegated to the #ButtonDiv element (thanks to bubbling).
If you do not want this behavior, just do that:
$('.Line1').on('click', function () {
var myVariable = this.id;
});
This is also correct:
$('.Line1').click(function () {
var myVariable = this.id;
});

get Contenteditable div html

Jsfiddle at demo.
I have a contenteditable div. I want the html of whatever I write in that div, on the click of anchor tag.
Right now, div is working but nothing is showing on click of the anchor tag.
function getcode()
{
var content = $('#my-contenteditable-div').html();
alert (content);
}
You can do this as well:
$("a").click(function () {
alert($('#my-contenteditable-div').html());
});
Here is the JSFiddle
Then you don't need to write separate functions and attach it to the onclick event attribute of the a tag
Try This
// get the link
var link = document.getElementById("linkId");
// add click listener to it
link.addEventListener("click",getcode,false);
// you handler
function getcode()
{
var content = document.getElementById("my-contenteditable-div");
alert (content.innerHTML);
}
Just you can go with jquery
Working Fiddle
$(document).ready(function() {
$('#gethtml').on('click', function(e) {
var content = $('#my-contenteditable-div').html();
alert (content);
});
});
can use this use id in a and a div to show data
<div contenteditable="true" id="my-contenteditable-div">
sdfsdfds
</div>
<a href="#" id="getcode" >Get HTML</a>
<div id="show"></div>
and jQuery
$( "#getcode" ).click(function() {
var contents = $('#my-contenteditable-div').html();
$("#show").text(contents);
});

toggle display in pure javascript

I am trying to toggle visibility of signup and signin boxes if sign in and sign up buttons are clicked. I am trying to use only pure javascript.
I wrote simple html and javascript as below:
<div>
<button class="signin">sign in</button><button class="signup">sign up</button>
<div class="signin-box" style="display: none;">
<form class="signin-form">
<label>username<input></label><label>password<input></label><button type="submit">signin</button>
</form>
</div>
<div class="signup-box" style="display: none;">
<form class="signup-form">
<label>username<input></label><label>password<input></label><button type="submit">signup</button>
</form>
</div>
</div>
javascript part:
var signupButton = document.getElementsByClassName('signup')[0];
var signinButton = document.getElementsByClassName('signin')[0];
var signupBox = document.getElementsByClassName('signup-box')[0];
var signipBox = document.getElementsByClassName('signin-box')[0];
console.log("box: ", signupBox, "button: ",signupButton);
var toggleVisible = function(item){
if (item.style.display === 'none'){
return item.style.display = 'block';
}else{
return item.style.display = 'none';
}
};
window.onload = function(){
signupButton.onclick = toggleVisible(signupBox);
signinButton.onclick = toggleVisible(signipBox);
};
The problem here is that the javascript toggleVisible is automatically activated even if i never clicked the buttons.
as a result, the signin-box and signup-box both gets display:block property.
How do i solve this problem?
You're calling the function, not passing it in. Just wrap your function call in an anonymous function:
signupButton.onclick = function() {
toggleVisible(signupBox);
};
If you don't care about older browsers, you can also simplify your code a little if you put your JavaScript at the bottom of the <body> tag and add a rule to your CSS:
document.querySelector('.signup').addEventListener('click', function() {
document.querySelector('.signup-box').classList.toggle('hidden');
}, false);
document.querySelector('.signin').addEventListener('click', function() {
document.querySelector('.signin-box').classList.toggle('hidden');
}, false);
And the CSS:
.hidden {
display: none;
}
I would recommend to use a standard JavaScript method addEventListener() to attached onclick event listener to the button.
It has following advantages over different solution:
You can attach an event handler to an element without overwriting existing event handlers.
You can add many event handlers of the same type to one element, i.e
two "click" events.
In your code it will look like
window.onload = function(){
signupButton.addEventListener("click", function() { toggleVisible(signupBox); });
signinButton.addEventListener("click", function() { toggleVisible(signipBox); });
};
Current code invokes toggleVisible(..) method and assigns its result to the button attribute, which is not one would expect.
signupButton.onclick = toggleVisible(signupBox);

Call a function when i click outside to the element like boot strap modal get closed

I have created a popup box of div. Which get shown when i click on an icon and get hide when i click on close button. But i want to get it closed if click out side of the popup. What i can do for that. I am using angular in my project and ng-show and ng-hide to show and hide the div. Any help is appreciable. Thanks in advance.
html code
<p ng-click="openPopUP()">openPopUp</p>
<div ng-show="popup">
<p>helo</p>
<p ng-click="closePopUp()">Close</p>
</div>
Java script
$scope.openPopUP = function(){
$scope.popup = true;
}
$scope.closePopUp= function(){
$scope.popup = false;
}
I just want to close if some one click out side the div
In your controller:
angular.element(document.body).on('click', function() {
$scope.$apply(function() {
$scope.closePopUp();
});
});
First of all read this post to get an idea how to close popups.
Fix for #pixelbits solution is to add $event.stopPropagation(); on popup div.
HTML
<p ng-click="openPopUP()">openPopUp</p>
<div ng-show="popup" ng-click="$event.stopPropagation();">
<p>helo</p>
<p ng-click="closePopUp()">Close</p>
</div>
JS
angular.element(document.body).on('click', function() {
$scope.$apply(function() {
$scope.closePopUp();
});
});
$scope.openPopUP = function(){
$scope.popup = true;
}
$scope.closePopUp= function(){
$scope.popup = false;
}

How to toggle the link in my case?

I am trying to toggle a link texts and content when user clicks the link.
I have something like
<a id='link' href='#'>click me</a>
<div id='items'>
<h1>title here</h1>
<p>texts here...</p>
</div>
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
})
When user click the link, the link text will become isClicked and the items html will be replaced with a image. However, if user clicks again, I want to see the link text changes back to click me and the items will hide the image and display the title and p tag contents again.
I am not sure how to accomplish this. Can anyone help me about it? Thanks a lot!
You can add a dummy class to the link and work with that condition
//Have a dummy class added to the link and toggle it on click
$('#link').on('click', function(e){
e.preventDefault();
var $this = $(this),
$textDiv = $('#items'),
$imageDiv = $('#image')
if($this.hasClass('clicked')) {
// remove the class
$this.removeClass('clicked');
// change the text
$this.text('click me');
// Hide image
$imageDiv.addClass('hide');
// show text
$textDiv.removeClass('hide');
} else {
// remove the class
$this.addClass('clicked');
// change the text
$this.text('isClicked');
// Show image
$imageDiv.removeClass('hide');
// Hide text
$textDiv.addClass('hide');
}
});
Check Fiddle
You can also chain the methods applied on the same element.
$('#link').on('click', function(e){
e.preventDefault();
if ($(this).text() == "isClicked") {
$(this).text("click me");
.. etc
} else {
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
}
});
Like I said in my comment, use a condition like this. Simple and effective.
One way you could do it:
$('#link')
// Set data attribute to hold original text
.data('primeText', $('#link').text())
// set click event using jQuery1.73+
.on('click', function(e) {
e.preventDefault(); // prevents going to link, not needed if you set link href to "javascript:void(0)"
// begin setting text, within is a inline-if statement testing current text against prime text
$(this).text($(this).text() == $(this).data('primeText') ? 'isClicked' : $(this).data('primeText'));
});
Another way, if you were working with more than one, like using a class name instead of ID:
$('.link')
// jQuery's .each method allows you to do things to each element in an object group
.each(function(i) { $(this).data('primeText', $(this).text()); })
// again, calling click method
.on('click', function(e) {
$(this).text($(this).text() == $(this).data('primeText') ? 'isClicked' : $(this).data('primeText'));
});
Examples
What about using a CSS approach?
Your HTML would stay the same:
<a id='link' href='#'>click me</a>
<div id='items'>
<h1>title here</h1>
<p>texts here...</p>
</div>
But we can use .toggleClass() here to make our lives easier
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').toggleClass('display-image');
})
The CSS would look like:
#items.display-image > h1,
#items.display-image > p,
{
visibility:hidden;
}
#items.display-image{
background-image:url("/images/image.png");
}
This way, you don't have to worry about removing things and .toggleClass handles their visibility.
You might have to do additional styling to get the image to work properly, or you may consider adding another element to contain the image and you can just set its visibility or display property
Try something like this:
HTML:
<a id='link' href='#'>click me</a>
<div id='items'>
<h1 class="text-item">title here</h1>
<p class="text-item">texts here...</p>
<img src="images/images.png" alt="Image" />
</div>
CSS:
img {
display: none;
}
JavaScript:
$('#link').off().on('click', function(e) {
e.preventDefault();
if($('#items > img').is(':visible')) {
$(this).text('click me');
$('#items > img').hide();
$('#items > .text-item').show();
} else {
$(this).text('isClicked');
$('#items > .text-item').hide();
$('#items > img').show();
}
});
Fiddle
You can try to store the value in a var and then toggle with on off in functions themselfs;
var initialState = $('#items').html(),
functionBla(e) {
e.preventDefault();
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
$('#link').off('click').on('click', functionCla);
},
functionCla(e) {
e.preventDefault();
$(this).text('click');
$('#items').html(initialState);
$('#link').off('click').on('click', functionBla);
};
$('#link').on('click', functionBla);
You can do it like,
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').children().toggle();
var img=$('#items img');
if(img.length>0){
img.remove();
}
else{
$('#items').append("<img src='images/image.png' />");
$(this).text('Click me');
}
})

Categories