JQuery Click does not effect window.onload - javascript

I have a trouble to fire window.onload event when I clicked, seem it doesn't work to me.
For example, when I clicked checkbox they will call function to render iframe with content. If you uncomment line 2 callOnLoad(), the iframe will be loaded with content, but this is not what I expect, I expect when the checkbox checked, the content in iframe will be rendered.
JSFiddle Demo

I assume that you want below thing:-
iframe will show on page-load(or on window-load),but the text appear/disappear when check-box checked/unchecked?
If yes do like below:-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type="checkbox" id="cgv" />
<div id="foo"></div>
</body>
<script>
$(document).ready(function() {
callOnLoad();
$('#cgv').on('click', function(e) {
if ($('#cgv:checked').length !== 0) {
$('#iframe').contents().find("body").append('Test <br/>' + new Date());
} else {
$('#iframe').contents().find("body").html('');
}
});
});
// Function render iframe
function callOnLoad() {
$("#foo").append("<div id=\"div-parent\"><iframe id=\"iframe\"></iframe></div>");
}
</script>

Check Fiddle
JS:
// Add your javascript here
$(function() {
$('#cgv').on('click', function(e) {
if ($('#cgv:checked').length !== 0) {
callOnLoad(); // Load iframe here, iframe does not work, the content does not render
} else {
$('#div-parent').remove(); // Remove div,
}
});
});
// Function render iframe
function callOnLoad() {
$("#foo").append("<div id=\"div-parent\"><iframe id=\"iframe\" class=\"active\"></iframe></div>");
var iframe = $("#foo").find('[id="iframe"]');
iframe.contents().find("body").append('Test <br/>' + new Date());
}
HTML:
<input type="checkbox" id="cgv" />
<div id="foo">
</div>

Related

How to make sure that the loaded file can be detected by a js code

I have this code in the file assets/URL.js:
$(function(){
$("a").on("click", function () {
event.preventDefault();
var TheURL = $(this).attr('href');
if(TheURL){
$("#MyDiv").load(TheURL , { name: '' },
function() {
alert("done");
});
}
});
});
And what it does is that if an <a> element is clicked, the function above prevents the page from going to that page then it gets the url and load it into the div with the id MyDiv.
Now this is the code of index.html:
<html>
<head>
<script type="text/javascript" src="assets/URL.js?v=1"></script>
</head>
<body>
<div id="MyDiv">
</div>
</body>
</html>
and the code of files/1.html is:
2
now, when I click on <a> in the file index.html the content of the <div> with the id MyDiv changes the the content of file/1.html without the page reloading.
But when I click <a> in the file file/1.html the page reloads and goes to file/2.html and doesn't follow the code in assets/URL.js, how can I force it to follow it and just replace the content of the <div> with the id MyDiv?
You need to setup the eventhandlers again when the dynamic html is loaded, right now you only bind the click event to the existing A tags in index.html, not the future ones in dynamic loaded content like 1.html
You could try something like:
$(function(){
RefreshEventHandlers();
});
function RefreshEventHandlers() {
$("a").on("click", function () {
event.preventDefault();
var TheURL = $(this).attr('href');
if(TheURL){
$("#MyDiv").load(TheURL , { name: '' },
function() {
alert("done");
RefreshEventHandlers(); // bind click to newly added A tags.
});
}
});
}
To make sure the click event handlers are set on all new A tags

Jquery checkbox to hide or display an element

I want to use jquery to always hide an element when it is checked, and show the element when it is unchecked. After doing some research I found the "is" attribute and so I created a simple html file as:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
if($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p id="test">This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<input type="checkbox" id="s">Click me</input>
</body>
</html>
Now for some reason, the jquery is not functional. Any help would be appreciated please. I also tried:
if(document.getElementById('isAgeSelected').checked) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
And this doesn't work either.
This is simple in javascript. Please try the following:
var cb = document.getElementById('isAgeSelected');
var txtAge = document.getElementById('txtAge');
$(document).ready(function(){
cb.change= function(){
if(cb.checked) {
txtAge.style.display ='block';
} else {
txtAge.style.display ='none';
}
};
});
In JQuery, you can do the following:
$(document).ready(function(){
$('#s').on('change', function(){
if($(this).is(":checked")){
$('#txtAge').show();
}
else{
$('#txtAge').hide();
}
});
});
You are only checking the checkbox once after the DOM is ready instead you should do it on its change event
$("#s").change(function(){
if($(this).is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
You can do this using following jQuery onchange event and .checked function
$(document).ready(function(){
$('#s').change(function(){
if(this.checked)
$("#test").hide(); // checked
else
$("#test").show();
});
});
Working URL:: https://jsfiddle.net/qn0ne1uz/
Good question !
now you were almost there.
$(document).ready(function(){ // <= !! you only evaluete the chackbox once (on document ready)
if($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
What you want to do is monitor checkbox the whole time, like so:
$('#s').bind('change', function() {
if ($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
example on jsfiddle
I'm guessing you are wanting to use the jQuery when the checkbox changes - at the moment you are just changing the hide / show it when the document loads.
Also ids need to be unique or jQuery will only get the first item with that id it comes to when you use the id selector. Change the test id to a class.
If you want the click me to change the state of the checkbox, turn it into a label (think you had it as a button) and target the input (using either for="input-id or wrap the label around the input and the text)
Try the following:
// this is to go in your document ready
$('#s').on('change', function() { // bind to the change event of the chackbox
// inside any change event, this is the js object of the thing that changed (ie the checkbox)
if (this.checked) {
$('.test').hide();
} else {
$('.test').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>This is a heading</h2>
<!-- ids need to be unique so change this to a class or your jquery won't work -->
<p class="test">This is a paragraph.</p>
<p class="test">This is another paragraph.</p>
<input type="checkbox" id="s"><label for="s">Click me</label>

Change the text of clicked element with 'this' in JavaScript / jQuery callback

Can anybody explain is this in the callback.
Example.
Web page.
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="myApp.js"></script>
</head>
<body>
<button type="button" id="btn001">Show</button><br/>
<p id="p001" class="article">Some contents...</p>
<button type="button" id="btn002">Show</button><br/>
<p id="p002" class="article">Other content...</p>
<!-- more paragraphs -->
</body>
</html>
First, I had written a function for each paragraph. Source code of the myApp.js.
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("#btn001").click(function () {
if ($(this).html() === "Show") {
$(this).html("Hide");
} else {
$(this).html("Show");
}
$("#p001").toggle();
});
// button 2 hides/shows second paragraph
$("#btn002").click(function () {
if ($(this).html() === "Show") {
$(this).html("Hide");
} else {
$(this).html("Show");
}
$("#p002").toggle();
});
// repeat code for next paragraphs
});
I get angry with the code repetition, so I tried excluding code to function.
function handleHideShow(par) {
if ($(this).html() === "Show") {
$(this).html("Hide");
} else {
$(this).html("Show");
}
par.toggle();
}
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("#btn001").click(function () {
handleHideShow($("#p001"));
});
// button 2 hides/shows second paragraph
$("#btn002").click(function () {
handleHideShow($("#p002"));
});
});
Toggling paragraphs works, but the text on the button is not changing. Can anybody explain what happens to this?
Why in the first example $(this) selects the clicked element?
What is $(this) in the second example?
And how to solve this problem?
Your first function is an event handler. With Event handlers $(this) automatically refers to the element that was clicked, changed, hovered, etc.. jQuery creates $(this) for you and, while you can't explicitly see it passed into the function it is available to all the code within the click handler's callback.
Your second function is a simple function and is not an event handler therefore jQuery does not create the $(this) reference for you
In your code, you could pass $(this) from your event handler like handleHideShow($(this),$("#p002")); and reference it in your function like function handleHideShow(btn, par). Then, inside handleHideShow, btn will refer to the same element as $(this) referred to in your click handler (see the second snippet below).
But, I would simplify the code alltogether by giving the buttons and paragraphs classes instead of ids and doing this:
$(document).ready(function () {
$('.article').hide();
$('.myBtn').click(function(){
$(this).html( $(this).html() == 'Show' ? 'Hide' :'Show' );
$(this).nextAll('.article').first().toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="myApp.js"></script>
</head>
<body>
<button type="button" class="myBtn">Show</button><br/>
<p class="article">Some contents...</p>
<button type="button" class="myBtn">Show</button><br/>
<p class="article">Other content...</p>
<!-- more paragraphs -->
</body>
</html>
Now, one could argue that this is less efficient as jQuery has to search through more elements to find the paragraph but I believe it to be more robust as you can add as many buttons and paragraphs as you like without worrying about all the sequential ids. And honestly, you'd have to have a pretty giant webpage to see any performance issues.
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("#btn001").click(function () {
handleHideShow($(this),$("#p001"));
});
// button 2 hides/shows second paragraph
$("#btn002").click(function () {
handleHideShow($(this),$("#p002"));
});
});
function handleHideShow(btn, par) {
if (btn.html() === "Show") {
btn.html("Hide");
} else {
btn.html("Show");
}
par.toggle();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="myApp.js"></script>
</head>
<body>
<button type="button" id="btn001">Show</button><br/>
<p id="p001" class="article">Some contents...</p>
<button type="button" id="btn002">Show</button><br/>
<p id="p002" class="article">Other content...</p>
<!-- more paragraphs -->
</body>
</html>
You need to pass the object of button in the function:
Try this:
function handleHideShow(par,that) {
if ($(that).html() === "Show") {
$(that).html("Hide");
} else {
$(that).html("Show");
}
par.toggle();
}
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("#btn001").click(function () {
handleHideShow($("#p001"),this);
});
// button 2 hides/shows second paragraph
$("#btn002").click(function () {
handleHideShow($("#p002"),this);
});
});
Or you try this also:
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("button[id^='btn']").click(function () {
if ($(this).html() === "Show") {
$(this).html("Hide");
} else {
$(this).html("Show");
}
$(this).next().toggle();
});
});
The above code is optimal and you can add buttons as many as you want.
The function is called with no special context, and this is not the element.
Reference the function instead
$("#btn001").click(handleHideShow);
$("#btn002").click(handleHideShow);
function handleHideShow() {
$(this).html(function (_, html) {
return html === "Show" ? "Hide" : "Show";
});
$('#' + this.id.replace('btn', 'p')).toggle();
}
FIDDLE

jQuery custom Confirm

I want to have a very simple custom dialog. When I click remove, I want a simple panel opens up with the option to confirm or cancel. If confirmed, more things will run.
Since I want to use this confirmation in different files, this was my approach:
In index.js that runs on all pages I have:
var confirmation = -1
$(document).ready(function(){
$('html').on({
click: function() {
confirmation = 1;
}
},'#confirmation_yes');
$('html').on({
click: function() {
confirmation = 0;
}
},'#confirmation_no');
});
function confirmAction(callback)
{
if( confirmation == 1 ) {
$('#popup_panel').slideUp('slow', function(){
$('#popup_fader').fadeOut('fast');
});
confirmation = -1;
callback(true);
}
if( confirmation == 0 ) {
$('#popup_panel').slideUp('slow', function(){
$('#popup_fader').fadeOut('fast');
});
confirmation = -1;
callback(true);
}
setTimeout(confirmAction, 50)
}
So my idea was that then inside other JS files, we have
$('#element').click(function(){
confirmAction(function(result){
// do my stuff
});
})
So when I do this, the system returns error and says "callback" is a not a function. What is wrong with this code?
Thanks
I made another approach. It is based on jQueryMobile but can also be used with normal jQuery after a few minor modifications. The basic is simple: you call a function that opens the popup and adds two buttons that react on functions that you provide by calling the opener-function. Here is my example:
function jqConfirm(data) {
var container = $('#genericConfirm');
container.find('h1').html(data.title); // title of the confirm dialog
container.find('p').html(data.message); // message to show
// .off('click') removes all click-events. click() attaches new events
container.find('.yes').off("click").click(data.yes); // data.yes/no are functions that you provide
container.find('.no').off("click").click(data.no);
container.popup({ positionTo: "window" }).popup("open"); // .popup("open") opens the popup
}
var confirmData = {
title: "Send this message?",
message: "Are you sure you want to send this message?",
yes: function() {
sendMessage();
$('#genericConfirm').popup("close");
},
no: function() {
$('#genericConfirm').popup("close");
}
};
jqConfirm(confirmData); // you open the popup with this function (indirectly)
And the HTML part (jQueryMobile specific, must be modified a bit to match plain jQuery)
<div data-role="popup" id="genericConfirm" data-overlay-theme="a" data-theme="c" style="max-width:400px;" class="ui-corner-all">
<div data-role="header" data-theme="a" class="ui-corner-top">
<h1>Title</h1>
</div>
<div data-role="content" data-theme="d" class="ui-corner-bottom ui-content">
<p style="margin-bottom: 15px;">Message</p>
<div class="ui-grid-a">
<div class="ui-block-a">
Cancel
</div>
<div class="ui-block-b">
Ok
</div>
</div>
</div>
</div>
Attach another handler to the button that deals with the logic. After you are done with the dialog, simply remove the dialog to get rid of the handlers. If you create an other dialog later, maybe with the same or an other layout, you can define different handlers for that dialog. As events 'bubble' up, both the handler on the button itself, as the handler on html (that only fires when the button is clicked), will be fired.
The following is merely pseudo-code, but it should give you an idea what you can do with this:
//This will create the html for your dialog
createMyFancyDialog();
showDialog();
//This is where you'll do the logic for this dialog
$('#confirmation_yes').on( 'click', function() {
doWhatEveryIWantToDo();
//After this dialog is done, destroy the dialog.
//This will get rid of the handlers we don't need in a future dialog.
//The handler attached to html will persist.
destroyDialog();
} );
$('#confirmation_no').on( 'click', function() {
doSomethingMean();
//After this dialog is done, destroy the dialog.
//This will get rid of the handlers we don't need in a future dialog.
//The handler attached to html will persist.
destroyDialog();
} );
I've tried to rewrite and fix your code, but there are too many things to adjust.
So, I strongly recommend you to rewrite your code in a simpler way, like this:
<button id="element">Element</button>
<div id="popup_panel" style="display: none;">
<p>Your msg?</p>
<button id="confirmation_yes" >Yes</button>
<button id="confirmation_no">No</button>
</div>
<script>
$(document).ready(function () {
$('#confirmation_yes').click(actionConfirmed);
$('#confirmation_no').click(actionNotConfirmed);
$('#element').click(showPopupPanel);
});
function actionConfirmed() {
$('#popup_panel').slideUp();
// User confirmed. Now continue.
// e.g. alert('Yes was clicked');
}
function actionNotConfirmed() {
$('#popup_panel').slideUp();
// User said no.
}
function showPopupPanel() {
$('#popup_panel').slideDown();
}
</script>
You can see this code in action here:
http://jsfiddle.net/LGTSK/
Keep it simple:
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input id='yes' type="button" value="Yes" data-result="Yes" />
<input id='no' type="button" value="No" data-result="No" />
<script type="text/javascript">
var result;
function confirmAction() {
if (result) alert(result);
else setTimeout(confirmAction, 100);
}
$(function() {
$('#yes, #no').on('click', function(e) {
result = $(this).attr('data-result');
});
confirmAction()
});
</script>
</body>
</html>

Day/Night mode - CSS + JQuery - Cookies?

I'm testing javascript code for day/light background switch and I don't know how to do something. I'm newbie to javascript, so I'm learning new stuff.
So what I want to do?
When I click for example on button "Day" (which change background to yellow), I want that style for yellow background stay in the code after page is refreshed. I heard something about Cookies/LocalStorage, but I don't know how to implement it for this code.
Feel free to change whole code if you know easier way to do this, but please explain why it's better or why it should be like that.
Thanks in advance for your help.
Here is the code:
HTML:
<body id="body">
<input type="button" onclick="day();" value="Day" />
<input type="button" onclick="night();" value="Night" />
<input type="button" onclick="reset();" value="Reset" />
</body>
CSS:
.darkSwitch {
background: #808080;
}
.lightSwitch {
background: #ffff99;
}
JavaScript:
function day() {
body.className = "lightSwitch";
};
function night() {
body.className = "darkSwitch";
};
function reset() {
body.className = "";
};
$(function() {
var button = $('input[type=button]');
button.on('click', function() {
button.not(this).removeAttr('disabled');
$(this).attr('disabled', '');
});
});
Last edit: now disabling selected button on page load, CODE NOT IN THIS POST, see the latest JSFiddle
Explanation
What I did:
The code is put in between<script> tags at the end of the <body> (personnal preference)
I added the parameter event to the onClick event of the button element.
I added event.preventDefault() at the start of the onclick event of the button element: ensuring the page is NOT refreshed on the click of a button.
Warning: ALL the buttons will behave the same in your page. If you have other buttons, I suggest you add another class for those three buttons and bind the event on the button.myClass element.
I added a condition on the button state change, so the reset button won't get disabled.
eval($(this).val().toLowerCase()+"();"); gets the value of the the clicked button and executes the function attached to it.
Solution
HTML
<body id="body">
<input type="button" class="changeBg" onclick="day();" value="Day" />
<input type="button" class="changeBg" onclick="night();" value="Night" />
<input type="button" class="changeBg" onclick="reset();" value="Reset" />
</body>
JavaScript
(JSFiddle) <-- Check this out Updated with classes & cookies
function day() {
body.className = "lightSwitch";
};
function night() {
body.className = "darkSwitch";
};
function reset() {
body.className = "";
};
$(function () {
/* RegEx to grab the "bgColor" cookie */
var bgColor = document.cookie.replace(/(?:(?:^|.*;\s*)bgColor\s*\=\s*([^;]*).*$)|^.*$/, "$1");
var button = $('input[type=button].changeBg');
button.on('click', function (event) {
event.preventDefault();
/* Executing the function associated with the button */
eval($(this).val().toLowerCase() + "();");
button.not($(this)).removeAttr('disabled');
if ($(this).val() != "Reset") {
$(this).attr('disabled', '');
/* Here we create the cookie and set its value, does not happen if it's Reset which is fired. */
document.cookie = "bgColor="+$(this).val();
}
});
/* If the cookie is not empty on page load, execute the function of the same name */
if(bgColor.length > 0)
{
eval(bgColor.toLowerCase()+'()');
/* Disable the button associated with the function name */
$('button[value="'+bgColor+'"]').attr("disabled","disabled");
}
});
I recommend you don't use cookies unless localStorage is not supported. They slow your site down.
if(localStorage){
localStorage.setItem("bgColor", "lightSwitch");
}else{
document.cookie = "bgColor=lightSwitch";
}

Categories

Resources