javascript dont work with jquery in the same page - javascript

I am having a problem with my code, which is a mix of jquery and plain javascript. I use jquery to show and hide some divs and the js to refresh a div by loading a page inside the div. The plain js code doesn't work as is, but if I delete the jquery code it works fine.
My code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ton plans</title>
<link href="template/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#refresh').fadeOut().load('last_post.php').fadeIn();
}, 10000);
</script>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
//no conflict jquery
jQuery.noConflict();
//jquery stuff
(function($) {
$(document).ready(function()
{
$("#bott_div").click(function() {
$("#div_profile").show(['fast'])
})
$("#page").click(function() {
$("#div_profile").hide(['fast'])
})
})
})
(jQuery);
</script>
</head>
There is a conflict between the jQuery code and the plain javaScript that is preventing it from working properly. I would require help identifying the problem.

Change the order of the first two scripts -- like this
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#refresh').fadeOut().load('last_post.php').fadeIn();
}, 10000);
</script>

There is a "(" in front of your function in jQuery code. Encapsulate code in a
$(document).ready(function() {
$("sampleSelect").click(function() {
//code
}
});

Related

How to write unit tests for events in backbone.js

I begin my adventure with write unit tests so please be indulgence. In my app I am using jQuery, backbone.js and underscore.js and for tests mocha.js and chai.js. I have problem because I have no idea how to test events using this tools. Fox example I have function which changes value of input. It call after change checkbox value.
test.html file:
<!DOCTYPE html>
<html>
<head>
<title>Backbone.js Tests</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="stylesheet" href="js/lib/mocha.css" />
<script src="js/lib/mocha.js"></script>
<script src="js/lib/chai.js"></script>
<!-- <script src="js/lib/sinon.js"></script> -->
<script>
// Setup
var expect = chai.expect;
mocha.setup('bdd');
// Run tests on window load event.
window.onload = function () {
(window.mochaPhantomJS || mocha).run();
};
</script>
<!-- App code -->
<script src="../public/static/js/libs/jquery-2.1.4.min.js"></script>
<script src="../public/static/js/libs/js.cookie-2.1.0.min.js"></script>
<script src="../public/static/js/libs/bootstrap.min.js"></script>
<script src="../public/static/js/libs/underscore-min.js"></script>
<script src="../public/static/js/libs/backbone-min.js"></script>
<script src="../public/static/js/libs/backbone-relational.min.js"></script>
<script src="../public/static/js/libs/backbone-super.min.js"></script>
<script src="../public/static/js/libs/handlebars-v4.0.5.min.js"></script>
<script src="../public/static/js/application.js"></script>
<script src="../public/static/js/main.js"></script>
<script src="../public/static/js/views/register.js"></script>
<script src="../public/static/js/views/modals/sign-in-modal.js"></script>
<script src="../public/static/js/views/modals/sign-up-modal.js"></script>
<script src="../public/static/js/helpers/forms.js"></script>
<script src="../public/static/js/helpers/alerts.js"></script>
<script src="../public/static/js/helpers/inpage-alerts.js"></script>
<script src="../public/static/js/collections.js"></script>
<script src="../public/static/js/models.js"></script>
<script src="../public/static/js/kodilla.lib.js"></script>
<script src="../public/static/js/views/knowledge-base.js"></script>
<script src="../public/static/js/libs/tether.min.js"></script>
<!-- Tests -->
<script src="js/spec/register.spec.js"></script>
</head>
<body>
<div id="mocha"></div>
</body>
</html>
register.js file:
App.Views.Register = Backbone.View.extend({
events: {
'click input[name="terms"]' : 'changeTermsConfirmation',
'click [type=submit]': 'onSubmitForm'
},
initialize: function(options) {
this.$termsConfirmedAtHidden = this.$('input[name="terms_confirmed_at"]');
},
changeTermsConfirmation: function(e) {
if ($(e.currentTarget).is(":checked")) {
this.$termsConfirmedAtHidden.val(Math.floor(Date.now() / 1000));
} else {
this.$termsConfirmedAtHidden.val('');
}
},
onSubmitForm: function() {
if (!this.$el.find('input[name="terms"]').is(':checked')) {
analytics.track('auth_register_not_checked_terms');
}
}
});
register.spec.js file:
$(document).ready(function() {
describe('Register Form', function() {
App.registerView = new App.Views.Register();
describe('initialize() function', function() {
it('Should initialize this.$termsConfirmedAtHidden variable by HTML object', function () {
expect(App.registerView.$termsConfirmedAtHidden).to.be.a('object');
});
});
describe('changeTermsConfirmation() function', function() {
it('Should set value of $termsConfirmedAtHidden element', function () {
//how to test this function
});
});
});
});
My question is how to write sensible unit test for "changeTermsConfirmation()" function. I'll be thankful for others notes, usage tips.
Maybe I can help you out with a few bits of info which might get you started.
Mocha/Chai is modular, so first you need to include a mocking/spying library into your project. The default choice for most people seems to be Sinon (along with Sinon-Chai).
Then you can examine and unit test your event handler:
Create a view instance for your test.
Set up a spy on the view method you want to test (changeTermsConfirmation in your case)
Trigger the event by calling trigger on your view instance
Your expectation can check how often your method has been called, and with which arguments, and what its return value has been.
If you don't care about any of that and just want to test view state changes, you don't need a spy (and you don't need to include a library like Sinon). Just create a view instance, call trigger and examine the result.

Javascript not working on page

I can't seem to get my javascript to work on my page, the same code works on another page, but not the one i'm using currently. the code is:
<script type="text/javascript">
function codeAddress() {
var $scores = $("#usersload");
setInterval(function () {
$scores.load("users.php #usersload");
}, 15000);
}
window.onload = codeAddress;
</script>
The above code should refresh a div on the page every 15 seconds, when the page loads, but does nothing, but on my other page it does what its suppose to.
if you need more code from my page let me know, but if you can help, thanks in advance!
Javascript on page:
<script>var init = [];</script>
<!-- Get jQuery from Google CDN -->
<!--[if !IE]> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- <![endif]-->
<!--[if lte IE 9]>
<script type="text/javascript"> window.jQuery || document.write('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">'+"<"+"/script>"); </script>
<![endif]-->
<!-- Pixel Admin's javascripts -->
<script type="text/javascript" src="assets/javascripts/bootstrap.min.js?parameter=1"></script>
<script type="text/javascript" src="assets/javascripts/pixel-admin.min.js?parameter=1"></script>
<script type="text/javascript">
init.push(function () {
// Javascript code here
});
window.PixelAdmin.start(init);
</script>
<script type="text/javascript">
function codeAddress() {
var $scores = $("#usersload");
setInterval(function () {
$scores.load("users.php #usersload");
}, 15000);
}
window.onload = codeAddress;
</script>
Could it be possible.
Have you added jQuery to the page yet, before this script block ofcourse.
The simplest way to do so..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Tried this on y page and this works
<script type="text/javascript">
function call(){
var $scores = $("#usersload");
$.post('user.php',{blankpost:''}, function(result){
$scores.html(result);
});
}
function codeAddress() {
setInterval( function(){
call();
}, 1000);
}
window.onload = codeAddress();
</script>
the blank post is ust to post something on the page, and just display the result
On the last line of your code, you have:
window.onload = codeAddress;
With that being said, shouldn't you still have to pass it an empty parameter such as the following?
window.onload = codeAddress();

$(document).ready(function () { ... won't fire

I have the following code at the end of one of my Views:
#section Scripts {
<script type="text/JavaScript">
$(document).ready(function () {
alert("!!!");
});
</script>
}
What ever I do, I can't get it to fire. I have checked and further up in the code JQuery is included. Using the suggestion here I changed my code to the following to confirm that jquery was correctly loaded. This gives the 'Yeah!' alert when loading the page.
#section Scripts {
<script type="text/JavaScript">
window.onload = function () {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
</script>
}
The end of the source in my page looks like:
<script src="/Scripts/jquery-1.9.1.js"></script>
<script src="/Scripts/jquery-ui-1.8.24.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/breakpoints.js"></script>
<script src="/Plugins/jquery-unveil/jquery.unveil.js"></script>
<script src="/Plugins/jquery-fademenu/jquery.fademenu.js"></script>
<script src="/Plugins/jquery-block-ui/jqueryblockui.js"></script>
<script src="/Plugins/jquery-slimscroll/jquery.slimscroll.js"></script>
<script src="/Plugins/bootstrap-select2/select2.js"></script>
<script src="/Plugins/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<script src="/Plugins/dropzone/dropzone.js"></script>
<script src="/Scripts/core.js"></script>
<script type="text/JavaScript">
$(document).ready(function () {
alert("!!!");
});
</script>
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Chrome","requestId":"6301d560dc274f4ea5ec24b8e0c2a19f"}
</script>
<script type="text/javascript" src="http://localhost:50280/1cd42285f06243669b1fd5837f1f05c3/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>
</html>
I can't work out where I am going wrong...
if this coode works properly
window.onload = function () {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
and this code doesn't :
$(document).ready(function () {
alert("!!!");
});
your likely problem is that there is a conflict with the dollar sign $
I would type out jQuery instead of using the dollar sign , or of course you can do something like this:
var j = jQuery.noConflict();
then you can do use the j where you used to use $
OR... there is simply just an error in the console that you still have not responded about , if that is the case I will update answer
EDIT::
The reasons that you code was not executing was because javascript is weird in the sense that if there is an error anywhere in the block of javascript code then nothing below it will be executed. That is why I asked if there were any console error's. Checking the console is the first step to solving any javascript error.
remove #section Scripts block put script block only and try... if not then remove all js use only jquery and try it will definatly. now add one by one script and find one which is conflicting. .

Why does this super simple jquery not work?

I'm having hard time getting this snippet to work. I have made a minimal example. You can view it online: http://jsfiddle.net/qnnZe/ where it is working!
test.html
<!DOCTYPE html>
<head>
<title>test</title>
<meta charset="utf-8">
<script src="jquery.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<p>I am going to test right now.</p>
</body>
</html>
test.js
$("p").click(function () {
$(this).hide("slow");
});
However, on my server it does not work. Here is the link to my server: http://techinf.de/sleepytime/test.html
As always, any help appreciated.
Because in jsFiddle your script code is executed after the DOM has loaded (that's the default option, see the dropdown set to "onDomReady"), on your page it's executed before that. It would work if you wrap your code in a ready() handler:
$(function()
{
$("p").click(function () {
$(this).hide("slow");
});
});
You need to wrap your click handler in a document ready function.
Try either:
$(document).ready(function () {
$("p").click(function () {
$(this).hide("slow");
});
});
or
$(function () {
$("p").click(function () {
$(this).hide("slow");
});
});
It will execute before the DOM is ready. Click handlers should be added in any of the normal jQuery "ready" methods, like:
$(function() {
$("p").click(function () {
$(this).hide("slow");
});
});

Java scripts conflict on my home page

<script type="text/javascript" src="jquery-1.js"></script>
<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript" src="slideshow.js"></script>
<script type="text/javascript">
//<![CDATA[
window.addEvent('domready', function(){
var data = {
'1.jpg': { caption: 'Volcano AsenciĆ³n in Ometepe, Nicaragua.' },
'2.jpg': { caption: 'A Ceibu tree.' },
'3.jpg': { caption: 'The view from Volcano Maderas.' },
'4.jpg': { caption: 'Beer and ice cream.' }
};
var myShow = new Slideshow('show', data, {controller: true, height: 400, hu: 'images/', thumbnails: true, width: 500});
});
//]]>
</script>
<script type="text/javascript">
$(document).ready(function()
{
//slides the element with class "menu_body" when paragraph with class "menu_head" is clicked
$("#firstpane p.menu_head").click(function()
{
$(this).css({backgroundImage:"url(down.png)"}).next("div.menu_body").slideToggle(300).siblings("div.menu_body").slideUp("slow");
$(this).siblings().css({backgroundImage:"url(left.png)"});
});
//slides the element with class "menu_body" when mouse is over the paragraph
$("#secondpane p.menu_head").mouseover(function()
{
$(this).css({backgroundImage:"url(down.png)"}).next("div.menu_body").slideDown(500).siblings("div.menu_body").slideUp("slow");
$(this).siblings().css({backgroundImage:"url(left.png)"});
});
});
</script>
<!--[if lt IE 7]>
<script type="text/javascript" src="unitpngfix.js"></script>
<![endif]-->
jQuery's no conflict is a great choice. I'd suggest though doing something like this:
<script language=javascript>
var $j = jQuery.noConflict();
</script>
That's going to give you access to jQuery's functionality using $j in place of $. I use this method to include jQuery in most pages via GreaseMonkey. I've got a custom copy of jQuery that includes the above call at the end. I use GreaseMonkey to insert a link to that script into the head of web pages so I can investigate object properties using $j without affecting other libraries that might be present in the page and using $.
After including jQuery, you should call $.noConflict(). This will remove the "$" from the global namespace:
<script type="text/javascript" src="jquery-1.js"></script>
<script>
$.noConflict();
</script>
<script type="text/javascript" src="mootools.js"></script>
At this point, you should use jQuery instead of $ if you want to call jQuery code. Or you could use a trick by wrapping the $ symbol in a closure:
<script type="text/javascript">
jQuery(function($) {
// here you can use $ instead of jQuery
});
</script>

Categories

Resources