Problems with event binding on dynamically created elements - javascript

I have code that is behaving one way on jsfiddle, one way on localhost, and another when uploaded to my website. I've been wrestling with the problem for a few days now. I don't know what tests or trial and errors I can run at this point.
This jsfiddle is working exactly as I want it to work.
http://jsfiddle.net/2ZLse/10/
When I insert this code into my project, and run it on localhost with WAMP, the javascript for the page does not work. The javascript is valid when run through jslint.
Stranger still, when I upload the exactly same files to my website, the javascript is functional, and I can even click on the watch button and render the form, but the nevermind button does not return me to the original state. I'm not receiving any errors on my cPanel.
When I replace
$(document).on('click', '.nevermind', function() {
$('#imagebox').html(imagebox);
});
with
$('.nevermind').click(function(){
$('#imagebox').html(imagebox);
});
The localhost will function the same as the website functions, with functioning javascript, but without a functioning nevermind button.
Below is the code, but let me tell you more about the rest of the page incase it's relevant. I'm using php. It's a .php file, bootstrap is loaded and working, jquery is loaded, and the javascript is run at the bottom of the page, not the header. There is ajax running elsewhere on the page, which works on the website but not the localhost, and I have the correct connect.php file for each. My best guess is that ajax has something to do with it.
What is the problem, or what tests can I run?
Here is the HTML
<div id="inputbox">
<form><button type="button" id="watchcontrol" class="btn btn-default">Watch</button>
</form>
<br>
</div>
<!-- images and continued input extension-->
<!-- imagebox also acts as control panel -->
<div id="imagebox">
ORIGINAL STATE
</div>
Here is the javascript.
var imagebox = 'ORIGINAL STATE';
var watchform = '<form action="post/watchpost.php" method="post">' +
'<input type="text" name="watchid" /><br>' +
'<input type="submit" class="btn btn-default" value="Contribute" />' +
'</form>' +
'<br><br><button type="button" class="btn btn-default nevermind">nevermind</button>';
$(document).ready(function(){
//control functionality
$(document).on('click', '.nevermind', function() {
$('#imagebox').html(imagebox);
});
$('#watchcontrol').click(function(){
$('#imagebox').html(watchform);
});
});
Event binding on dynamically created elements?
This question, while helpful, did not solve my issue. I believe my issue is separate from that one.

The following only binds event handler to the EXISTING DOM element:
$('.nevermind').click(function(){
$('#imagebox').html(imagebox);
});
which does not include what you append after clicking on #watchcontrol.
The following would work though, binding the event everytime when you create the dynamic element (even though I suggest that you free the element before removing it from the DOM):
$('#watchcontrol').click(function(){
$('#imagebox').html(watchform);
$('.nevermind').click(function(){
$('#imagebox').html(imagebox);
});
});
http://jsfiddle.net/2ZLse/11/

Related

Jquery script doesn't work in jquery loaded page

I have tried to search for similar questions, but I could not find anything, so if you know any similar question please let me know.
Let me explain what Im doing:
I have a script that validates forms in a js file, It works fine in any page with a form I have, the problem is that when I load a form using jquery it just doesn't work, I have tried using the next line in different places: Header, footer, etc
<script src='myFile.js'></script>
By far the only thing that has worked for is writing the line of code above inside the form itself.
I think it has something to do with the form that the DOM works, I have also tried using and not using it.
$(document).ready(function (){ //code});
It only will work when I add the script tag with the src attribute inside the form itself.
It would not represent a big problem for me to add the script tag to any form I load using jquery but it's a little bit more of work an unefficient, and also when I add the script tag to any form and load it using ajax I get the next console warning that only goes away when I remove the script tag from the form file:
jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
Here is a part of my code:
<!--home.html-->
<div id='formFrame'>
</div>
<script>
$("#formFrame").load("html/loginForm.html");
</script>
<!--end of home.html-->
<!--loginForm.html-->
<form action='somePage.php' method='post' id='loginForm'>
<input type='email' name='email' placeholder='email'>
<input type='password' name='password' placeholder='password'>
<input type='submit' name='submit' value='Login'>
</form>
<script src='js/validate.js'></script>
<!--end of loginForm.html-->
<!--validation script (validate.js)-->
$(document).ready(function (){
$("#loginForm").submit(function (e){
e.preventDefault();
alert("Working");
});
});
Thanks for spending some of your valuable time on reading this, I appreciate it a lot!
As I can't comment, putting my comment in answer!
I am not sure what you have written in validate.js, but if you are using jQuery unobtrusive validation, then you must rebind the validators to the form if you are loading it dynamically.
I was facing same issue in ASP.NET MVC while loading forms using AJAX. I am not sure will it help you or not but below is the code.
$("#formFrame").load("html/loginForm.html", function(){
var $form = $("formSelector");
$form.removeData('validator');
$form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($form);
});
Well guys I found a solution:
As there seems to be a conflict when loading an external page using ajax (.load) I opted to use php instead of javascript which worked fine:
I removed the next code
<script>
$("#formFrame").load("html/loginForm.html");
</script>
And added the next to the div where I want to load my content:
<!--home.php (changed html to php)-->
<div id='formFrame'>
<?php
require 'html/loginForm.html';
?>
</div>
I would have prefered to use the load method from ajax to avoid loading the content befere the user could request it, but by far that's the only solution I have been able to think about.
Thanks to everybody for your help it was really helpful!

Rails App Javascript Unobtrusive

I'm having trouble with javascript in my rails app. I want to run a simple multiplication function on click when myButton is clicked and return it in an alert. Right now, I can't even get the JS to talk, and it's reloading the page, despite the code I have...
<script>
$(function() {
$('#myButton').click(function(e) {
e.preventDefault();
alert("hello")
})
})
</script>
<form>
$<input id="dataToPass"type="text"></input> <input id="myButton "type="submit" value="Invest"> </input>
</form>
If I add inline JS, I can get the alert to work, but when I move the code outside of the html, it's not working. Anyone know why? I'm not adept with jQuery or JavaScript.
change
id="myButton "
with
id="myButton"

Execute custom script after page loaded with Ratchet\Push.js

So on the GitHub documentation for Ratchet 2.0.2 I found the following statement.
Script tags containing JavaScript will not be executed on pages that
are loaded with push.js. If you would like to attach event handlers to
elements on other pages, document-level event delegation is a common
solution.
Can someone please spell out exactly how to get a custom <script> to execute after being loaded by Push.js?
On my first page, I have a Table view, with several links to other pages, one of them being a link to a second page with a Twitter Feed widget on it.
<li class="table-view-cell media">
<a class="navigate-right" href="Twitter.php" data-transition="slide-in">
<span class="media-object pull-left icon icon-person"></span>
<div class="media-body">
Twitter Feed
</div>
</a>
</li>
The second page only contains the twitter feed widget code. When I browse to this page directly (without being loaded by Push.js) everything loads correctly, but when it is loaded via Push.js, the script is not executed.
Can someone please explain what I need to do to get this script to execute after being loaded by Push.js? I've searched Google, Stack Exchange, and Github\Ratchet issues and have not been able to find a good example of how to accomplish this.
One solution would be to add data-ignore="push" to the link, but I want to know how to do with WITH push.js.
<div class="content">
<a class="twitter-timeline" href="https://twitter.com/XXXX" data-widget-id="XXXX">Tweets by XXX</a>
</div>
<script>
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
</script>
EDIT: below was how I originally solved this problem, which worked fine, but I came up with a better solution, which I posted as the answer to this question.
I finally figured it out.
On your first page, you need to do the following...
var checkPage = function(){
//Only run if twitter-widget exists on page
if(document.getElementById('twitter-widget')) {
loadTwitterFeed(document,"script","twitter-wjs");
}
};
window.addEventListener('push', checkPage);
checkPage() will execute for every time a new page is loaded via push.
Just made a change for Ratchet.js to make individual js works for each page more elegant.(https://github.com/mazong1123/ratchet-pro)
By using the new ratchetPro.js, we can do followings:
(function () {
var rachetPageManager = new window.RATCHET.Class.PageManager();
rachetPageManager.ready(function () {
// Put your logic here.
});
})();

How to clear a server-side html file's content, from input type button

I'm new to PHP. I want to use a (HTML) input type = button to make the content of a HTML empty.
I searched the web, if I use fopen(file.html,w+), it will clear the files content:
"w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist)".
Source: http://www.w3schools.com/php/func_filesystem_fopen.asp
My problem is that there is probably a bit of code missing or syntax mistakes, because when I press the button nothing happens.
I really don't know and couldn't find anything on the world wide web, it's probably really simple. Sorry in advance if I wrote the question wrong.
HTML code
<input type="button" name="clearlog" id="clearlog" value="Clearlog" class="btn btn-default">
PHP code:
<?php
// clear log
if(isset($_POST['clearlog']))
{
function cleartlog()
{
$fp = fopen("log.html", 'w+');
fwrite($fp, "");
fclose($fp);
}
}
?>
The PHP code is in an external file, but is required it in my index.php.
PS: is it better to use the ftruncate function?
Source: http://www.w3schools.com/php/func_filesystem_ftruncate.asp
What you're trying to do here is far beyond the scope of your current understanding. You don't have anything associating that button to any code. Either the button needs to be part of a form that submits to a php file, or you need a javascript click event listener added to it which will then send an ajax request to the server (php) to call your php code.
Form submission directly to a php file (requires a page load) is a mostly outdated practice. Using Ajax is preferred.
The logic is simple:
Attach a javascript click event listener to the button.
The click function will send an ajax request to a page where your php code to run.
jQuery is not necessary, but with jQuery, the ajax call could be as simple as $.get('foo.php). and then whatever php code on foo.php will be executed.
You should use a form which will connect to the server and the PHP should clear the log.html file.
<form action="wipeFileContents.php">
<input type="submit" value="Clear Log File">
</form>
It will be the simplest solution, although you can go the harder AJAX way which is theoretically faster, but requires you to learn javascript.
you could try the following:
HTML
<form action='myfile.php'>
<input type="submit" value="clear">
</form>
PHP
if(isset($_POST['clear']))
{
file_put_contents("log.html", "");
}

get back to previous page

just i want to make back button in my site. once i click the button it need to take the url in to previous page. how can i make this using jquery?
<button type="button" onclick="history.back();">Back</button>
the answer by wRAR is correct, you can use history.back or history.go(-1). However, if you are using ajax, you might need a bit more than that.
Stephen Walter has a nice article on how to use jQuery, ASP.NET, and Browser History which basically describes how to save and restore the application state yourself. I recommend you give a read.
Elijah Manor(co-host of the Official jQuery Podcast) has also written a nice article about this topic.
I hope this helps
-D
Try this: am using materialise css.
<button id="back_btn" class="btn waves-effect waves-light" name="action">Back<i class="material-icons left">chevron_left</i>
</button>
In your jquery script file add
$("#back_btn").click(function (){
window.history.back();
});
within the document ready function.
For JQM, this works!
$(document).ready(function(){
$('.backLink').click(function(){
parent.history.back();
return false;
});
});
This is what I have successfully used in one of my recent projects:
<script>
function goBack() {
window.history.back();
}
</script>
<a href="#" onclick="goBack()" class="btn-event-show-video">
Return to Stand
</a>
I think button onclick="history.back();" is one way to solve the problem.But it might not work in the following cases:
If the page gets refreshed or reloaded.
If the user opens the link in a new page.
To overcome these, the following code could be used if you know which page you have to return to.
E.g. If you have a no of links on one page and the back button is to be used to return to that page.
<input type="button" onclick="document.location.href='filename';" value="Back" name="button" class="btn">

Categories