how to make ngclick work like toggle? - javascript

i have taken a span and after clicking the span, it adds 1 to it. but what i need is, ngclick should add only once to whatever value is inside the span. Again for another click it should subtract 1 from it. It should not iterate continuously.
i am getting {{tvshow.episode.ratings.loved}} from json data.
pls help.
//html
<html>
<body>
<span class="label likeme" ng-click="tvshow.episode.ratings.loved = tvshow.episode.ratings.loved + 1" ng-init="{{tvshow.episode.ratings.loved}}">
<i class="icon-thumbs-up"></i> {{tvshow.episode.ratings.loved}}</span>
</body>
</html>

//view.html
<span ng-click="doOneTimeOnly();">{{tvshow.episode.ratings.loved}}</div>
//controller.js
$scope.times = 0;
$scope.doOneTimeOnly = function () {
if ( $scope.times < 1) {
//do my stuff with the tvshow.episode.ratings.loved
//.................
$scope.times += 1;
}
}
Actually i dont think this makes sense but is what you are asking for :P
this can also be easily moved to a custom directive like directive('ngOneClickOnly'); for example

now here you have one option ng-disabled with this you can click only once.
<script>
angular.module("my_app",[])
.controller("my_ctr",function($scope){
$scope.skm=true;
$scope.mmmmmm=function()
{
if($scope.skm==false)
{
alert("first time you clicked");
}
else
{
alert("now you cant click");
$scope.skm=false;
}
}
})
</script>
<body ng-app="my_app" ng-controller="my_ctr">
<button ng-click="mmmmmm()" ng-disabled="!skm">hii</button>
</body>

Related

Have to click twice to execute onclick

I have problem where I have to click twice to swap button text and class on the first time I click it. All the other times it changes on first click.
I already tried removing click inside changeUnits() function but in this case I can change to Celcius once and cannot swap values anymore. I'm assigning value and class because I'm going to use it later in another api call to retrieve weather in specified units.
Does anyone see what am I doing wrong?
html
<button id="units" class="Fahrenheit" onclick="changeUnits();callWeather()">F</button>
javascript
function changeUnits() {
if($("#units").hasClass("Fahrenheit")) {
$(".Fahrenheit").click(function() {
$(".Fahrenheit").text("C");
$(this).removeClass('Fahrenheit').addClass('Celcius');
});
}
else if($("#units").hasClass("Celcius")) {
$(".Celcius").click(function() {
$(".Celcius").text("F");
$(this).removeClass('Celcius').addClass('Fahrenheit');
});
}
}
try this .. No need to check for class you only need toggleClass() and just check for .text() to change the text to C or F
function changeUnits(el) { // pass el here
var ThisText = $(el).text(), // get text from this element
fah_or_ce = $(el).text().trim() == 'C' ? 'F' : 'C'; // set fah_or_ce as a variable and check if C return F and if else return C
$(el).text(fah_or_ce ); // change text with new text
$(el).toggleClass('Fahrenheit Celcius'); // toggle between classes
}
and use it onclick = "changeUnits(this)"
Demo 1
function changeUnits(el) {
var ThisText = $(el).text(),
fah_or_ce = $(el).text().trim() == 'C' ? 'F' : 'C';
$(el).text(fah_or_ce );
$(el).toggleClass('Fahrenheit Celcius');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="units" class="Fahrenheit" onclick="changeUnits(this)">F</button>
And for me I prefer to use .on(click) event instead of inline onclick
Demo 2
$(document).ready(function(){
$('#units').on('click' , function(){
changeUnits(this);
// you can use callWeather() as well
//callWeather();
});
});
function changeUnits(el) {
var ThisText = $(el).text(),
fah_or_ce = $(el).text().trim() == 'C' ? 'F' : 'C';
$(el).text(fah_or_ce );
$(el).toggleClass('Fahrenheit Celcius');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="units" class="Fahrenheit">F</button>
I don't understand what why you use the function changeUnits only when button is click. For me it should be more when $("#units") change class. But it will be better to use this code for you :
<button id="units" class="Fahrenheit" onclick="changeUnits();callWeather()">F</button>
<button id="units" class="Celsius" onclick="changeUnits();callWeather()" style="display: none;">C</button>
function changeUnits() {
if($("#units").hasClass("Fahrenheit")) {
$(".Fahrenheit").hide();
$(".Celcius").show();
}else if($("#units").hasClass("Celcius")) {
$(".Fahrenheit").show();
$(".Celcius").hide();
}
}
There you go :
Explanation:
Your problem is quite simple, the fact that you have to press twice is due to the fact that your function that really does the swap is affected once you click,
a simple idea is to assign your function when the document loads
Working code, that is really similar to yours:
function initialize()
{
if($("#units").hasClass("Fahrenheit"))
{
$(".Fahrenheit").click(function()
{
$(".Fahrenheit").text("C");
$(this).removeClass("Fahrenheit").addClass("Celcius");
$(this).click(initialize());
});
}
else if($("#units").hasClass("Celcius"))
{
$(".Celcius").click(function()
{
$(".Celcius").text("F");
$(this).removeClass("Celcius").addClass("Fahrenheit");
$(this).click(initialize());
});
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body onload="initialize()">
<button id="units" class="Fahrenheit">F</button>
</body>
</html>

Detect changes made to input through code

Somewhere in my page I have an button that when clicked changes the value of another input. However I don't have control over the code where the click event is defined (on a clients' CDN) and I didn't bother to look. I just want to capture the event when my inputs' value is change through the code. Here's an example:
HTML
<input type="text" id="myinput" />
<input type="button" id="theonechanging" value="Click Me" />
<br />
<p id="message"></p>
JS
var i = 0;
$("#theonechanging").click(function(e) {
// YOU CAN NOT CHANGE THIS FUNCTION
$("#myinput").val("changed via button " + i++);
});
$("#myinput").on("input change bind",function(e) {
$("#message").text("changed " + i++);
});
Here's a fiddle where you can test the situation: http://jsfiddle.net/fourat05/t9x6uhoh/
Thank you for your help !
There's an incredibly hacky way to do this.
What you do is replace the jQuery.fn.val function with your own implementation, and call the old implementation from the new one. This technique is a kind of Monkey patching.
The implementation is as follows:
var i = 0;
$("#theonechanging").click(function(e) {
// YOU CAN NOT CHANGE THIS FUNCTION
$("#myinput").val("changed via button " + ++i);
});
var handleChanges = function(){
$("#message").text("changed " + i);
}
var oldval = jQuery.fn.val;
jQuery.fn.val = function(){
oldval.apply(this,arguments);
if(this.attr('id') === 'myinput'){ //and possibly add a check for changes
handleChanges();
}
}
$("#myinput").on("input change bind",function(e) {
i++;
handleChanges();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="myinput" />
<input type="button" id="theonechanging" value="Click Me" />
<br />
<p id="message"></p>
However, I strongly recommend against using it, because:
This alters the behaviour of a widespread library, thus creating possible pitfalls for the developers producing code for the same page
It will quickly become complicated to detect multiple events on multiple elements.
Please understand the side effects of this method before implementing it.
Values changed directly in the DOM dont trigger those events, but since you have an action that is called to change the value, you can trigger the input change event.
$("#theonechanging").on("click", function(e) {
$("#myinput").trigger("change");
});
fiddle
use triggers
var i = 0;
$("#theonechanging").click(function(e) {
// YOU CAN NOT CHANGE THIS FUNCTION
$("#myinput").val("changed via button " + i++);
});
$("#theonechanging").on("click", function(e) {
$("#myinput").trigger("change");
});
$("#myinput").on("input change bind",function(e) {
$("#message").text($("#myinput").val());
});
Fiddle
I think it is not possible without changing the script for BUTTON.
When the user click the 'Button', you should trigger another function to catch the change in 'Input'.
If you don't want to change the 'Button' script, you can try something like the code below, seeking for the correct combination of events:
(check the list of events here: http://www.w3schools.com/tags/ref_eventattributes.asp)
<html>
<body>
<input type="text" id="myinput" onchange="change_Message('onchange')"
onclick="change_Message('onclick')"
oninput="change_Message('oninput')"
onkeypress="change_Message('onkeypress')"/>
<input type="button" id="theonechanging" value="Click Me" onclick="change_Input()"/>
<br />
<p id="message"></p>
<script>
var input_value = document.getElementById('myinput').value; // as global variable
function Test_if_Change()
{
if ( document.getElementById('myinput').value != input_value )
{
change_Message('Test_if_Change');
}
}
setInterval(Test_if_Changed, 10);
function change_Input() { document.getElementById('myinput').value = 'input changed by button'; }
function change_Message(event) { document.getElementById('message').innerHTML = 'message changed by '+event+' to: ' + document.getElementById('myinput').value; }
</script>
</body>
</html>
There is no perfect way to detect input value changes through code but if you you are using jquery ,you can hook the val function and trigger change event manually.
jQuery.fn._val = jQuery.fn.val;
jQuery.fn.val = function(){
jQuery.fn._val.apply(this,arguments);
if(arguments.lenght==1){
this.trigger('code-change');
}
}
}

jQuery .click() doesn't fire but console.log shows output

I'm having a problem in my code where I click a DOM-element using JavaScript. The click does not work and I am almost sure it is no dumb programming mistake (always dangerous to say).
After deleting some DOM-elements I want my code to click an element and trigger its onclick event. However this doesn't work. According to my code the event triggers but the event doesn't happen and the click event returns the jQuery object.
HTML:
<div class="castor-tabs">
<div class="castor-tab" data-path="../SiteBuilding/alertbox.js" data-saved="saved" data-editor="5475c897f1900editor">
<span class="castor-filename">alertbox.js</span>
<span class="castor-close"><i class="fa fa-fw fa-times"></i></span>
</div>
<div class="castor-tab" data-path="../SiteBuilding/index.php" data-saved="saved" data-editor="5475c89903e70editor">
<span class="castor-filename">index.php</span>
<span class="castor-close"><i class="fa fa-fw fa-times"></i></span>
</div>
<div class="castor-tab active" data-path="../SiteBuilding/makesite.php" data-saved="saved" data-editor="5475c8997ac77editor">
<span class="castor-filename">makesite.php</span>
<span class="castor-close"><i class="fa fa-fw fa-times"></i></span>
</div>
</div>
JavaScript:
$(".castor-tabs").on("click", ".castor-close", function() {
var tab = $(this).parent();
if(tab.attr("data-saved") == "saved") {
// File is saved
if($(".castor-tab").length > 1) {
// 1 element is 'tab' the other is a second tab
if(tab.next().length > 0) {
// If element is to the right
window.newTab = tab.next();
} else if(tab.prev().length > 0) {
// If element is to the left
window.newTab = tab.prev();
}
} else {
window.newTab = false;
}
var editor = tab.attr("data-editor");
$("#" + editor).remove(); // textarea linked to CodeMirror
$("#" + editor + "editor").remove(); // Huge CodeMirror-element
tab.remove();
if(window.newTab) {
console.log("window.newTab.click()");
console.log(window.newTab.click()); // Simulate click()
}
} else {
// File isn't saved
}
});
The onclick event:
$(".castor-tabs").on("click", ".castor-tab", function() {
$(".castor-tab.active").removeClass("active");
$(this).addClass("active");
var editor = $(this).attr("data-editor");
$(".CodeMirror").hide();
$("#" + editor).show();
});
I saved the element in the window object for a reason. After the code runs and it skips the click-part I still have the DOM-element i want to click saved in the window object. This means I can run
console.log(window.newTab.click());
again. Surprisingly this does click the element and this does activate the click-event. It also returns the DOM-element instead of the jQuery-object.
The image shows in the first two lines the failed click. The third line is my manual input and the fourth line is the successful return value of the click().
I hope you can help me to solve this.
UPDATE
.trigger("click") unfortunately gives the same output..
UPDATE 2
To help you i made the website available on a subdomain. I know many of you hate it if you have to go to a different page but I hope you'll forgive me because in my opinion this cant be solved through JSFiddle.
The link is http://castor.marknijboer.nl.
After clicking some pages to open try closing them and you'll see what i mean.
try adding return false; at the end, when binding .castor-close click event
$(".castor-tabs").on("click", ".castor-close", function() {
var tab = $(this).parent();
if(tab.attr("data-saved") == "saved") {
// File is saved
if($(".castor-tab").length > 1) {
// 1 element is 'tab' the other is a second tab
if(tab.next().length > 0) {
// If element is to the right
window.newTab = tab.next();
} else if(tab.prev().length > 0) {
// If element is to the left
window.newTab = tab.prev();
}
} else {
window.newTab = false;
}
var editor = tab.attr("data-editor");
$("#" + editor).remove(); // textarea linked to CodeMirror
$("#" + editor + "editor").remove(); // Huge CodeMirror-element
tab.remove();
if(window.newTab) {
console.log("window.newTab.click()");
console.log(window.newTab.click()); // Simulate click()
}
} else {
// File isn't saved
}
return false;
});
Instead of simulating a click, why not just pull the click logic out of your click function and just call the javascript function using the arguments that you'll need to perform your business logic?
Your code is working but not able to trigger click event binded to castor-close because i tag is empty. Put some text in it and check
<span class="castor-close"><i class="fa fa-fw fa-times">Click me</i></span>
DEMO
Your click handler has the requirement that the click target should have the class castor-close but when you are calling click via JavaScript you are clicking the parent element instead (.castor-tab), and the click handler doesn't react.

If jQuery has Class do this action

I am trying to check whether or not a particular element has been clicked but am having trouble doing so. Here is my HTML:
<div id="my_special_id" class="switch switch-small has-switch" data-on="success" data-off="danger">
<div class="switch-on switch-animate"><input type="checkbox" checked="" class="toggle">
<span class="switch-left switch-small switch-success">ON</span>
<label class="switch-small"> </label>
<span class="switch-right switch-small switch-danger">OFF</span>
</div>
</div>
Here is my jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
</script>
I am guessing that my id "my_special_id" is not what is actually being clicked?
I guess click event should have event parameter.
$(document).ready(function() {
$('#my_special_id').click(function(e) {
if (e.target check condition) {
window.alert('ON!');
}
});
});
parameter 'e' above specified is the event object that has all info about click event.
so if u check all info under 'e.tartget', u will be able to find out which one is clicked.
Hope it's helpful for you.
Cheers :)
Since you are looking for a alert when the checkbox is clicked
$(document).ready(function() {
$('#my_special_id input.toggle').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
Demo: Fiddle
Simply put alert when you click on that particular class switch-on
<script type="text/javascript">
$(document).ready(function() {
$('#my_special_id div:first-child .switch-on').on('click',function() {
window.alert('ON!');
});
});
</script>
Or even try like
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($(this + 'div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
This JavaScript works for me.
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
alert("On!");
}
});
});
You are sure you have JQuery?
Your code looks fine I think either you have a syntax error somewhere else or you do not have JQuert.
does this alert?
$(document).ready(function() {
alert("Jquery works");
});
The click event will trigger to whatever you're bound do. the only time you'd have to be worried is if you bound to both a parent and child (e.g. you had listed #my_special_id,.switch-small--then you'd have to look at e.target).
With that said, you can use scope to limit how jQuery finds the div:first-child. I'm not 100% sure what you're after, but the below appears to do what you're after:
$(document).ready(function() {
$('#my_special_id').click(function() {
// look for div:first-child within `this` (where `this=#my_special_id`
// per the .click selector above)
if ($('div:first-child',this).hasClass('switch-on')) {
window.alert('ON!');
}
});
});
If you're looking to bind to the on/off separately, you may want to change it around a bit. we can still check for .switch-on, just have to traverse differently:
// here we bind to the on/off buttons and not the container
$('#my_special_id .switch-small').click(function(){
// you want the facsimilee of `div:first-child`, so (because we're now
// within that node, we use .parent() to get back up to it
var $firstChild = $(this).parent();
if ($parent.hasClass('switch-on')){
alert('ON!');
}
});

javascript functions to show and hide divs

Hello I have the following 2 JavaScript functions to open up a div and to close it.
<script>
function show() {
if(document.getElementById('benefits').style.display=='none') {
document.getElementById('benefits').style.display='block';
}
}
</script>
<script>
function close() {
if(document.getElementById('benefits').style.display=='block') {
document.getElementById('benefits').style.display='none';
}
}
</script>
Here is the html:
<div id="opener"><a href="#1" name="1" onclick=show()>click here</a></div>
<div id="benefits" style="display:none;">
some input in here plus the close button
<div id="upbutton"><a onclick=close()></a></div>
</div>
For some reason the show function works how it should, but the close button does not do its job. So if there is someone who could help me out I really would appreciate. Thanks a lot.
<script>
function show() {
if(document.getElementById('benefits').style.display=='none') {
document.getElementById('benefits').style.display='block';
}
return false;
}
function hide() {
if(document.getElementById('benefits').style.display=='block') {
document.getElementById('benefits').style.display='none';
}
return false;
}
</script>
<div id="opener">click here</div>
<div id="benefits" style="display:none;">some input in here plus the close button
<div id="upbutton"><a onclick="return hide();">click here</a></div>
</div>
I usually do this with classes, that seems to force the browsers to reassess all the styling.
.hiddendiv {display:none;}
.visiblediv {display:block;}
then use;
<script>
function show() {
document.getElementById('benefits').className='visiblediv';
}
function close() {
document.getElementById('benefits').className='hiddendiv';
}
</script>
Note the casing of "className" that trips me up a lot
The beauty of jQuery would allow us to do the following:
$(function()
{
var benefits = $('#benefits');
// this is the show function
$('a[name=1]').click(function()
{
benefits.show();
});
// this is the hide function
$('a', benefits).click(function()
{
benefits.hide();
});
});
Alternatively you could have 1 button toggle the display, like this:
$(function()
{
// this is the show and hide function, all in 1!
$('a[name=1]').click(function()
{
$('#benefits').toggle();
});
});
You need the link inside to be clickable, meaning it needs a href with some content, and also, close() is a built-in function of window, so you need to change the name of the function to avoid a conflict.
<div id="upbutton">click to close</div>
Also if you want a real "button" instead of a link, you should use <input type="button"/> or <button/>.
check this:
click here
<div id="benefits" style="display:none;">some input in here plus the close button
<div id="upbutton"><a onclick="close(); return false;"></a></div>
</div>
Rename the closing function as 'hide', for example and it will work.
function hide() {
if(document.getElementById('benefits').style.display=='block') {
document.getElementById('benefits').style.display='none';
}
}
Close appears to be a reserved word of some sort (Possibly referring to window.close). Changing it to something else appears to resolve the issue.
http://jsfiddle.net/c7gdL/1/
You can zip the two with something like this [like jQuery does]:
function toggleMyDiv() {
if (document.getElementById("myDiv").style.display=="block"){
document.getElementById("myDiv").style.display="none"
}
else{
document.getElementById("myDiv").style.display="block";
}
}
..and use the same function in the two buttons - or generally in the page for both functions.

Categories

Resources