Move JS code from HTML to source in HEAD section - php

I have a problem, and I would like you to guide me to solve it if you do not mind ...
In my HTML source code had several pieces of css codes here and there. So I decided to put together into a file called principal.css and do the following in the head section
<link href="css/principal.css" rel="stylesheet" type="text/css" />
This has worked wonderfully!
My idea was to do the same with the javascript code in my HTML, but it has not worked. This is one of them:
$("[data-slider]")
.each(function () {
var input = $(this);
$("<span>")
.addClass("output")
.insertAfter($(this));
})
.bind("slider:ready slider:changed", function (event, data) {
$(this)
.nextAll(".output:first")
.html(data.value);
});
Is there some special way to do this?
My goal is that the page has the least amount of code, I leave well indented, documented and clean.
Greetings, I will await your answers in!
Please, excuse my english...

You need to wrap this in $(document).ready(...)
Also, it has unusual indentation. It would probably be better to format it like this:
$(document).ready(function() {
$("[data-slider]").each(function () {
var input = $(this);
$("<span>").addClass("output").insertAfter($(this));
}).bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first").html(data.value);
});
});
I personally don't like chaining so many commands like this in a row. It might be SLIGHTLY more efficient, but it makes it much more difficult to debug and fix problems. I personally would break the .each() and the .bind() into separate statements. But I suppose it's a matter of preference.

.ready() documentation
$(document).ready(function(){
// your code here
});
or
.load() documentation
$(window).on('load', function(){
// your code here
});

Place your js code in a separate .js file. Similar to how CSS is also placed in a separate file and then link it to your html file.
like so, in your html file:
<script src="somejsfile.js"></script>
And yes, you have to wrap your js code in a document.ready function so it can execute when the documents elements are finished loading.
For example:
$(document).ready(function() {
// Your JS code here
});
This is because the browsers HTML interpreter reads code from TOP to BOTTOM, so if your not setting a document.ready, the JavaScript will run before any of your document elements are loaded.

Head:
<head>
<link href="css/principal.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="myscript.js"></script>
</head>
myscript.js
$(function() {
$("[data-slider]")
.each(function () {
var input = $(this);
$("<span>")
.addClass("output")
.insertAfter($(this));
})
.bind("slider:ready slider:changed", function (event, data) {
$(this)
.nextAll(".output:first")
.html(data.value);
});
});

I would like to add that if you plan on putting your js code in a separate file which is a good idea. You should be aware that you will not have to use the...
<script>
//js code
</script>
...the script tags in a separate js file.

Related

jQuery Function that fires when a select value has been changed?

Good day guys. So I'm trying to work on this simple jQuery program that triggers a function whenever and only whenever a select value has been changed. I plan to use this simple function in a more complex program once I make it work.
This is the code (it came from jQuery API website, and I modified it slightly to try what I wanted to happen):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>change demo</title>
<style>
div {
color: red;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<select id="selector" name="sweets">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div></div>
<script>
$( "#selector" )
.on('change',(function () {
$( "select option:selected" ).each(function() {
<?php header("Location:jcue.php")?>
});
})
.change();
</script>
</body>
</html>
What I want to happen is that, the page should only redirect to jque.php once the select input value has been changed. But what's happening in the program is that it automatically redirects to another page without even loading the current page itself. What's the problem? jQuery and Javascript are the unexplored foreign lands for me in web programming, and I know this is pretty basic to many web programmers, but I just need it (and I really have to start learning Javascript, AJAX, and jQuery when I get to have free time haha).
The complex program I'm going to use it to is a search results filtering program. But before I can do that, I have to make this simple program work.
Can anybody help me? Thank you. Answers will be greatly appreciated.
Try this instead::
$(function() {
$("#selector").change(function() {
location.href = "jcue.php";
});
});
This will fix your issue.
The problem is because your PHP gets executed as soon as the page loads - you cannot incorporate it as you have into javascript. Also, you don't need the each() within the handler. Try this instead:
$("#selector").on('change',(function () {
window.location.assign('jcue.php');
});
JavaScript is client-side script, while PHP is server-side. You are trying to trigger a PHP header redirect which should happen at server-time before it's sent to the client's browser. So this will not be working in that on change event.
Simply use:
$("#selector").change(function() {
window.location = "jcue.php"; //this can be URL as well
});
P.S. I noticed you have two "selected" options, mind tell why?
Not so good practice: to redirect using Javascript, since JS can be blocked
There were some syntax errors, here's a fix, just replace your code.
$( "#selector" ).on('change',(function () {
var str = "";
$( "select option:selected" ).each(function() {
window.location.replace("http://stackoverflow.com");
});
}));
Good Practice: use jquery ajax requests Jquery Ajax or redirect using standard php header function(which has to run before your html/js is loaded)
Good luck, learning programming. It's fun!

Add Heading Before dynamically created form field Jquery .insertBefore

I have a form that is dynamically created, so I can't edit the layout of the form itself. However, I want to add a title above one of the text input fields in the form. I have given that field a unique css ID and am using the following script to try and add my heading before it:
<script type="text/javascript">
$('<h5 class="form_title">Calculate Return</h5>').insertBefore('#price');
</script>
For some reason this won't work though, can anyone think why that might be. Here is the page in question
http://www.theres-a-thought.com/client-yourdream/?page=property_submit
Add document ready to your code -
<script type="text/javascript">
$(document).ready(function() {
$('<h5 class="form_title">Calculate Return</h5>').insertBefore('#price');
});
</script>
Looking at your page, I don't see where #price is defined. Maybe it is added later via JS and i missed it..
You are using jquery in no-conflict mode, and you need to wrap your code in document ready..
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('<h5 class="form_title">Calculate Return</h5>').insertBefore('#price');
});
</script>
Running this; however, has no affect on the page(from what i can see).
The code below works because the ID exists. It isn't what you are trying to accomplish, but it should get you started.
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('<h5 class="form_title">Calculate Return</h5>').insertBefore('#property_name');
});
</script>

Pass PHP output to jQuery

I have got this code
/* Popup for hot news */
$(document).ready(function() {
var $dialog = $('<div></div>')
.html('text to be shown')
.dialog({
autoOpen: false,
title: 'Table'
});
This code is in my JavaScript files which are included by header.php.
How to pass PHP output to this function?
Inputing <?php echo($mydata)?> in .html('') above does not solve anything.
Any reason why this gives an error?
Thanks for helping!
First of all your code is having some problem, $ in php is a prefix of variable and $ in jQuery is a selection sign. You can view the html source(the output) on browser for debug.
I can think of three ways to do so:
(1)The way you have mentioned should work, see the code below
<?php $foo='hi'?>
<script>
alert("<?php echo $foo?>");
</script>
(2)Another way is to separate server side and client slide code clearly for better maintenance
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<?php echo"<div id='foo' style='visibility:hidden;'>HI</div>"?>
<script>
alert($('#foo').text());
</script>
(3)The last way is by passing variable from the URL http://example.com/example.php#hi
<script>
var foo= location.href.split('#')[1];
alert(foo);
</script>
Adding <?php //code?> to your JS files do nothing because JS files are not executed by Apache. You can either use Ajax to request for data once your page loads (if the data doesn't need to be there at start) or you can add those PHP code blocks to your HTML code.
Using Ajax (goes in your JS file)
$(document).ready(function(){
var u = 'data.php';
var d = {};//data
$.get(u, d, function(data){
//got by data. lets invoke some methods here
});
});
Putting it in your HTML (goes in your HTML file)
var __DATA = '<?php //output some data I prepared earlier ?>';
//I'm using __ and capitol case to denote a global variable. Just personal preference
<script src='myjsfile.js' type='text/javascript'></script>
//the variable __DATA is available to your JS file and you can use it

Multiple jquery Scripts on one page

I am brand new to Jquery and have run into something that if answered will help greatly in the future. I have 2 very simple questions
I am using codeigniter, HTML5 and all php pages as well.
I have a menu 'aside' with 4-5 sections that I want to be able to close to save space. So I am using 2 simple slideToggle scripts.
$("a").click(function () {
$('#cat').slideToggle('slow', function() {
})
});
and
$("button").click(function () {
$('#dog').slideToggle('slow', function() {
})
});
The problem is, if I use button on both, both scripts operate even though I am requesting the script to run on 2 different ID's ( I know the dog and cat thing is silly, I just threw them in to see if a fake id would work and it did)
The question is, how can I use button OR a href on both scripts to preserve my styling?
My second question is can you put multiple scripts on a .js file for inclusion and how would you do it? Does each get script tags or some other kind of separator?
Thanks for helping, these are my first two scripts. At least they work :)
<div class="menu">
<h2>News Links</h2>
Display
<!--
if I use "button" here, both scripts run on tandem
-->
<script>
$("a").click(function () {
$('#cat').slideToggle('slow', function() {
})
});
benchmark->mark('links_start');
$this->db->order_by('id', 'DESC');
$this->db->limit('10');
$query = $this->db->get('links');
foreach ($query->result() as $row)
{
echo "link \" title=\"$row->title\" target=\"_blank\">$row->name ";
}
$this->benchmark->mark('links_end');
?>
</ul>
</div>
</div>
<div class="menu">
<h2>Archives</h2>
<button>Display</button> <!--if I use "a" here, both scripts run on tandem
-->
<script>
$("button").click(function () {
$('#dog').slideToggle('slow', function() {
})
});
</script>
<div id="dog">
<?php
$this->db->order_by('id', 'DESC');
$where = "publish";
$this->db->where('status', $where);
$this->db->select('id, title', FALSE);
$this->db->select('DATE_FORMAT(date, "%b %D %Y")AS date');
$this->db->from('posts');
$query = $this->db->get();
foreach ($query->result() as $row)
I think what you want is something like this:
<button id="news_display">Display News</button>
<button id="archive_display">Display Archive</button>
$("#news_display").click(function () {
$('#news').slideToggle('slow');
});
$("#archive_display").click(function () {
$('#archive').slideToggle('slow');
});
This uses jQuery id selectors for the click events, as you already did in the anonymous functions. That way, they're specific and independent.
You can used combined selectors:
$("a, button").click(function () {
$('#cat').slideToggle('slow');
});
That will allow you to run the same function when either an a or a button is clicked.
My second question is can you put multiple scripts on a .js file for inclusion and how would you do it? Does each get script tags or some other kind of separator?
A javascript 'script' generally refers to a file included by the script tag, although that usage is ambiguous.
What you've got in your post is a javascript statement, probably inside a script tag on your page:
<script type="text/javascript">
function helloWorld() {
alert('Hello world');
}
</script>
You can do this (inline to the page), or move the contained code out to a .js file and reference it:
<script type="text/javascript" src="myjavascript.js"></script>
Your myjavascript.js file would look like this:
function helloWorld() {
alert('Hello world');
}
myjavascript.js can contain as much javascript as you'd like. Common approaches are to put grouped functionality into a single javascript file, and include it in the page. This makes it easy to re-use the javascript you've written across multiple pages by including it with the script tag on each page that makes use of it (I assume you've done this with the jquery javascript library already).
You can do the exact same thing that jquery has done, and dump all your javascript into a .js file and use script to load it into your page.
In re: your 2nd question: The code you posted
$("a").click(function () {
$('#cat').slideToggle('slow', function() {
})
});
… is one statement. You can write as many statements as you'd like into a single javascript file or <script> tag. If you have multiple JavaScript files, you can concatenate them into one file and reference that file from a script tag.

Load script before function

I want to use a function on my html page but the content is delivered via ajax, how do I first load the script and then apply the function ? It won't work if I include the script in my <head> . Also how can I use the jQuery .find() and and apply a function or modify the css for content that has been delivered after the page has loaded ?
LABjs(http://labjs.com/) has an awesome interface for that. Here's an example code.
<!-- In the head -->
<script src="lab.js"></script>
<!-- In the body -->
<script>
$LAB
.script("yourscript.js")
.wait(function(){
yourfunction();
});
</script>
In the above example, the yourfunction(); will only be called after the script yourscript.js has been loaded.
Edit: After an ajax call using the .load method, this is how your body script might look like.
<script>
$('taggetelmselector').load(your_url, data, function(){
$LAB
.script("yourscript.js")
.wait(function(){
yourfunction();
});
});
</script>
See http://api.jquery.com/load-event/
jQuery has this functionality built in to the getScript function.
$.getScript('yourscript.js', yourfunction);

Categories