How to toggle two words on click event - javascript

I want to toggle open and hide words when I toggle the panel.
Here is the code I used. it works only for hide but when I click next time it doesnt show open.
$(document).ready(function(){
$(".flip1").click(function(){
$(".panel1").slideToggle("slow");
var val= 0;
if(val==0){
$('#word').html("hide").show();
val=1;
}else{
$('#word').html("open").show();
val=0;
}
// $(".info").hide();
});
});
help me to correct this.

Move this line:
var val= 0;
Out of the click() callback.
Where you have it it is a local variable within your click handler, and it gets set to 0 every time the handler is called. Move it outside the handler and it will get initialised to 0 once, and then updated within the click handler.
Alternatively, get rid of that variable altogether and do something like this:
$(document).ready(function(){
$(".flip1").click(function(){
$(".panel1").slideToggle("slow");
$("#word").html(function(i,oldHtml) {
return oldHtml==="hide"?"show":"hide";
}).show();
});
});
Demo: http://jsfiddle.net/9S5eq/
EDIT: If you pass a callback to the .html() method, jQuery calls it for each element in the jQuery object, passing the index of the current element within the object and that element's current html. It sets the html to whatever value you return. So in this case where there is only one element the index parameter isn't actually needed at all, but you can't leave it out because the current value is passed in the second parameter (so i is just a sort of placeholder).

you can use this code
$(document).ready(function(){
var val= 0;
$(".flip1").click(function(){
$(".panel1").slideToggle("slow");
if(val==0){
$('#Word').html("hide").show();
val=1;
}else{
$('#Word').html("open").show();
val=0;
}
// $(".info").hide();
});
});
you must use var val=0 before the click event of the .flip1

Related

jquery not changing src of element

I have a select element in my HTML, i then have an iframe that displays PDFs. i have some jquery code that should change the "src" attribute of the iframe when a user selects an option but so far i cant seem to get it to trigger. when i click an option from the select nothing happens. i have tried using .change() and .on("change") but they do not work. i have console.log within the function but it does not log anything into the console.
The jquery
$(document).ready(function(){
var x = $("#demo-category").val();
$("#demo-category").on("change", "#demo-category", function(){
$("#readframe").attr("src", x);
console.log(x);
console.log("test");
});
});
should you need any more information i will provide it if i can.
Event delegation (that is, your
.on("change", "#demo-category", function(){
) is for when the element that triggers the event is different from the element that the listener is added to. When you want to add a plain listener to a single element, don't pass another selector - if you do that, the listener won't fire. Instead just call .on('change', fn....
Also, you're retrieving x on document load. Retrieve the new value after #demo-category changes instead:
$(document).ready(function() {
$("#demo-category").on("change", function() {
var x = $(this).val();
$("#readframe").attr("src", x);
console.log(x);
console.log("test");
});
});
I think this will work
$(document).ready(function(){
$("#demo-category").on("change", function(){
$("#readframe").attr("src", $(this).val());
});
});

onClick function used on dynamic content not working properly

I hit a problem with the onclick function when i add divs with ids like "n_block"+(1-~). When I use the jquery zoom function on the objects to make them smaller or bigger onClick doesn't work anymore. I'm not really good at programming so the code might be kind of confusing.
Heres the code i use for the onClick of items:
$(document).on("click",function (e, ui){
//When the document gets clicked, check if one of the items was clicked.
if($(e.target).is($("#n_block" + cloneCount1)) || $(e.target).is($("#n_block" + cloneCount1+ " span"))){
//Set current item.
var item = $("#n_block" + cloneCount1);
//Set style to current item.
item.css("border-color", "Black");
item.css("border-width","2px");
item.css("background-color", "floralwhite");
jsPlumb.repaintEverything();
//Check if key Delete was pressed while item selected & delete that item with his children.
$('html').keydown(function(e){
if(item.css("border-width")=="2px"){
if(e.keyCode == 46) {
/* Prevents line bugging*/
jsPlumb.detachEveryConnection();
jsPlumb.deleteEveryEndpoint();
var razred = getClass(item, "b_"),
id = item.prop("id");
item.remove();
if(razred == "b_2"){
$(".ovoj."+id).remove();
}
else if (razred == "b_4"){
$(".ovojLoop."+id).remove();
$(".empty_block_c."+id).remove();
}
if ( $('.objects').find('div').length == 2) {
$(".objects").empty();
$(".objects").append('<div class="b_s" id="start_block">START</div><p id="start_text">Insert symbols here!</p><div class="b_s" id="end_block">STOP</div> ');
}else{
/* Connects objects together with line. ****/
povezi(cloneCount, tip_crte, ".objects");
}
}
jsPlumb.repaintEverything();
}
});
}
// If item is not clicked set this css to the current item.
else{
$("#n_block" + cloneCount1).css("border-width","1px");
jsPlumb.repaintEverything();
}
});
And heres the zoom code for zooming in when button is clicked:
var currentZoom = 1.0;
$(".zoomin").click(function (){
//Detaches the connections from item to item.
jsPlumb.detachEveryConnection();
jsPlumb.deleteEveryEndpoint();
//Prevents spamming of button, animates the objects
$(".project").stop().animate({ "zoom": currentZoom += .1}, "slow", function() {
if(!$(".objects").children().is($("p"))){
povezi(cloneCount, tip_crte, ".objects");
}
});
});
Use event delegation for binding events to dynamically added elements.
$(document).on('click', ".zoomin", function (){
//Your code.
});
When you use normal .click() to bind event to an element, then that even gets bound to only those elements which exist in the DOM at the moment of the execution of code. Using event delegation, you can tell jQuery that we need to add the handler to every '.zoomin' element which comes inside a particular element no matter when it is added.
The solution depends when exactly is the script which tries to bind the events are executed.
For Eg: Lets assume this script is in document ready function of jquery
$(document).ready(function(){
$(".zoomin").click(function (){
//your logic here
});
});
Here this script is executed when the page HTML is completed loading into the browser. Now when the script executes it tries to find a element with the class zoomin and if found it will add a event to that element and move on. If the element is not found the script just moves on. So we should actually take care of when the script is executed and is the intended element available at that particular instant of time. If the element is not yet available in the HTML (element might come in later dynamically using jquery) we have 2 options to bind event to the element.
1) Execute the script when the element is being added into the HTML: Lets say I have a event which brings up a pop up with some image. Now I want to zoomin and zoomout the image. Since the image in the popup is added dynamically and I have control of when its being added, I can do this.
$(document).ready(function(){
$('.ViewImage').on('click',function(){
// some code is executed which brings up the popup
// now we know that the image is added into html we can now run the script
$(".zoomin").click(function (){
//your logic here
});
});
});
2) We have no Clue/ Control when the element is added into HTML but still want to bind a event to it: This is scenario where we have no control on when the element is being added or not sure where it is being added from (might be from some external plugin used etc) or not having control at all on the element which is added. Thats when we use this syntax as suggested by #Rejith R Krishnan
$(document).on('click', ".zoomin", function (){
//Your code.
});
This will work on all the elements which are in the HTML at the time of execution of the script and on the elements which will be added in the future with the class name zoomin. So this script can be placed inside/ outside of jquery document ready event

How to replace onClick event dynamically?

I have following page:
<body>
foo
</body>
</html>
<script type="text/javascript">
function func(k){
alert(k);
$('#key').click(function() {func(++k)});
}
</script>
My expectations of this code execution following:
I click on link and see 0, then click one more time and see 1, then click one more time and see 2....then 3....4...5....6
But actual result:
I click on link and see 0,
I click on link and see 0 and then 1 twice,
I click on link one more time and see 0 2 2 2 2 and 1.
Please help to understand what does happen and and how to rewrite it?
Update
Key of the question is invocation of old function with new argument on onclick action!
you can set a global variable and increase in each function call
var globalCounter = 0;
$('#key').click(function() {
alert(globalCounter);
globalCounter++;
});
you dont need
onclick="func(0)"
in html tag because you already set click event handler with
$('#key').click(function(){});
You can simply modify your function as follows:
function func() {
if (!window.count)
window.count = 0;
alert(count++);
}
foo
Side notes:
You should add the <script> block inside your <html> document, preferably just before closing <body>
You are missing quotes around the id attribute
I rewrote function like this:
function func(k){
alert(k);
$("#key").removeAttr('onclick');
$("#key").unbind('click')
$('#key').click(function() {func(++k)});
}
and I see expected result
Currently, the inline click handler is setting k to 0 and adding a new jQuery click listener on every click. Each jQuery handler will increase the value of k on every click, and this creates a mess you can see in the alerted values.
At first, remove the inline onclick from #key. You can do it without breaking anything, just set it to null within $(document).ready():
$('#key').prop('onclick', null);
Then for the click counter, create a variable and a new click handler:
var clickCounter = 0;
$('#key').click(function () {
clickCounter += 1;
});
A live demo at jsFiddle.
You are adding a new func on each click. That is why you are seeing the new number many times, as well as the old ones.
Add these lines to remove previous handlers:
$("a").prop("onclick", null); //remove default "onclick" handler - otherwise the 0 will always continue coming
$("#key").off("click"); //remove old jQuery assigned handlers
Then send ++k to new handler.

Call a function as if an event called it

I have the following function:
bringToFront : function () {
"use strict";
Desktop.appZ += 1;
this.style.zIndex = Desktop.appZ;
}
This function get's called when certain elements are clicked:
appWindow.addEventListener("mousedown", Desktop.bringToFront, false);
appWindowParent.appendChild(appWindow);
However, if I add some elements to the DOM and click them, thus increasing their z-index, and then add another element, this element will appear behind the first elements, instead of in front of them. So when I add "appWindow" to "appWindowParent", I also want to call "bringToFront" on "appWindow". I need to do this without chaining the "bringToFront" function (i.e. without adding arguments).
Thanks!
By the way, I know I could just increase the z-index manually when I create the element, but I intend to do more things in the "bringToFront" function and I don't want to duplicate that code.
You can use apply() to set the value of this inside the function
appWindowParent.appendChild(appWindow);
Desktop.bringToFront.apply(appWindow);
Detect by following code if a new element is inserted into dom
$(document).on('DOMNodeInserted', function(e) {
if (e.target.id == 'someID') {
}
});

jQuery wait for above code execution to complete

I've written some javascript using jQuery to replace any select lists with a div and ul alternative so that it will give me some more styling control and make the drop downs look the same cross browser. The below code works 99% for me but I have one issue. At the bottom of the code I have had to use .delay() to tell the code in a way to wait for the .each() loop above to finish doing what its doing. The problem with this is that there is atleast one second untill the replacement happens leaving a flash of the old select boxes. Also I can forsee another problem is what if it takes more than one second for the each() loop to complete...
How can I get the code at the bottom to only run once the each loop has run and complete. Also I welcome any optimizations on the rest of the code.
EDIT: Some of the HTML has been stripped from the code so I have pastebinned it: http://pastebin.com/4HFLjHE1
// Check when ready
$(function() {
// Find dropdowns
$("select.dropdownreplace").each(function() {replaceDropDown(this);});
// If document clicked anywhere hide drop downs
$(document).click(function(event){
$("div.dropdownreplace ul").hide();
});
});
function replaceDropDown(that) {
// Create HTML for new drop down
// hidden field
var hiddeninput = $('');
// div
var dropdowndiv = $(''+$(":selected", that).text()+'');
// loop through values and make li's
$("option", that).each(function() {
$("ul", dropdowndiv).append(''+$(this).val()+''+$(this).text()+'');
// set click handler for this drop down
$(dropdowndiv).click(function() {
$("ul", this).show();
return false;
});
// set click handler for link items
$("a", dropdowndiv).click(function() {
// Get name of hidden input
var nameofdropdown = $(this).parent().parent().parent().attr('id');
var nameofinput = nameofdropdown.replace("dropdownreplacement_", "");
// set hidden input value to whats been clicked
$("[name='"+nameofinput+"']").val($(this).parent().find("span").text());
// set div
$("div#"+nameofdropdown+" > span").text($(this).text());
$("div#"+nameofdropdown+" ul").hide();
return false;
});
});
// Remove drop down then add in replacement html
$(that).delay(1000).after(hiddeninput);
$(that).delay(1100).after(dropdowndiv);
$(that).delay(1200).remove();
}
Thnaks
Scott
Inside your function, compare the index jquery passes you, with the total number of items you have.
I don't know your html, but I believe you can do this.
Change your function so it receives the index param that jquery sends.
$("option", that).each(function(index) {
Then, at the end of that function compare the length with the index, if they are the same, then you're done
if ( $('option', that).length == (index +1 ) ) {
$(that).after(hiddeninput);
$(that).after(dropdowndiv);
$(that).remove();
}
From my tests, this should be what you need. Don't know if there is a more "standard" way to do it.
Hope this helps
What you have to do is create a callback functionl. In your each(), after the initial function you can indicate it has to do some more things when it's finished:
$("option", that).each(function() {
<...code...>
}, function() {
<...code...> //this gets performed after the previous function is complete
});

Categories

Resources