how to convert an html script into a .js file script - javascript

would like to place the script into a .js file that opens already with
$(document).ready(function() {
});
I have tried but it feel slike because im putting the onMouse over command into the html I don't think it will be possible?
<head>
<style>
div > p {
cursor: pointer;
}
</style>
<script>
var monkeySrc = "http://icons.iconarchive.com/icons/martin-berube/animal/256/monkey-icon.png";
var lionSrc = "http://icons.iconarchive.com/icons/martin-berube/animal/256/lion-icon.png";
var treeSrc = "http://totaltreeworks.co.nz/wp-content/uploads/2011/02/Tree-256x256.png";
var falconSrc = "http://icons.iconarchive.com/icons/jonathan-rey/star-wars-vehicles/256/Millenium-Falcon-01-icon.png";
function changeImage(src){
document.getElementById("myImage").src = src;
}
</script>
</head>
<body>
<div class="images">
<img id="myImage" width="256" height="256">
</div>
<div>
<p onmouseover="changeImage(monkeySrc)">Monkey are funny!</p>
</div>
<div>
<p onmouseover="changeImage(lionSrc)">Lions are cool!</p>
</div>
<div>
<p onmouseover="changeImage(treeSrc)">Trees are green!</p>
</div>
<div>
<p onmouseover="changeImage(falconSrc)">Falcons are fast!<p>
</div>
</body>
</html>

If you were to take your existing JavaScript and place it in an external file, it would work just fine. It would work because all of your variables and your function would be in the global scope.
Going one step further you'll want to move those onmouseover event handlers into the JavaScript itself.
Given a small change to your current HTML and assuming jQuery you could do something like the following:
<p data-kind="monkey">Monkey are funny!</p>
then
var urlMap = {
monkey : 'http://icons.iconarchive.com/icons/martin-berube/animal/256/monkey-icon.png'
...
};
$('p').on('mouseover', function () {
var kind = $(this).data('kind');
var url = urlMap[kind];
changeImage(url);
});
which you would then be able to wrap in the $(document).ready, the shorthand for which is just $(function () { /* The code from above here */ });

You would need to bind the event handlers programmatically from within the .js file. jQuery would make this very simple and allow you to use arbitrary CSS selectors, but you can do the same in pure JS using e.g. document.getElementById and document.addEventListener.

You can bind the function to the event using Javascript addEventListner
1- Add id attribute to each of your paragraphs tags
<p id="p1"> .....</p>
2- Grab a variable that points to each of those
var p1 = document.getElementById('p1');
3- add event listner
p1.addEventListener("mouseover", changeImage(monkeySrc));

If you put your javascript code in another file and replace <script>...</script> with <script src="javascriptcodefilename.js"></script> in your HTML file, it still works as intended.
Example: http://codepen.io/anon/pen/waLqxz

It might be cleaner to add all of your urls to an array where the key is the name of the link, so you would have something like urls['lionSrc'] = "www.xyz.com";...
then in your changeImage function you would do document.getElementById("myImage").src = url[src];
this way you could even check to see if the image exists already, and if not, show an "image not found" icon.

Related

How to insert code before the root div "__next" js

When creating a next JS app you always have a root div just after the body div like this:
<body>
<div id="__next">
I am using a Javascript plugin that requires me to insert some code immdiately after the body tag. Like this:
<body>
//My code here
<div id="__next">
Is it possible to do this? If so How?
Yes, you can do using a prependTo function of JQuery as follows:
$(document).ready(function () {
$('<input type="text">').prependTo('body');
// in your case it would be
$('<div id="__next">').prependTo('body');
});
I have found the answer to my question is to create a _document.js file. This will over-ride the defult document that is created by next.
Documentation here: https://nextjs.org/docs/advanced-features/custom-document

Jquery Clone() inner HTML attributes not changing

I have the following code, and when the function Add2List() is executed, it appends the template without having the changes made.
Whats wrong here?
<script type="text/javascript">
function Add2List(data, index){
var $list_item = $('#list-template').clone();
$list_item.find('.box-list').attr("id", "list_"+data.id);
$list_item.find('a.list_link').attr("href", data.link);
$list_item.find('.list_photo').attr("src", data.photo);
$('#listings_list').append($list_item.html());
console.log($list_item.html());
}
</script>
<script id="list-template" type="text/x-custom-template">
<div class="box-list">
<a class="list_link" href="#">
<img src="" class="list_photo">
</a>
</div>
</script>
You're cloning the <script> tag instead of the html inside. Use $( $('#list-template').html() ) instead (demo)
function Add2List(data, index){
var $list_item = $($('#list-template').html());
$list_item.attr("id", "list_"+data.id);
$list_item.find('a.list_link').attr("href", data.link);
$list_item.find('.list_photo').attr("src", data.photo);
$('#listings_list').append($list_item);
console.log(data, $list_item.html());
}
I believe the issue is with jquery not handling the html correctly because it is inside the script tag (or it is a DOM issue).
Doing
var $list_item = $('<div>', {
html: $('#list-template').html()
});
instead of cloning it fixes the problem.
What it does is to create a div element in memory that holds the contents of the template (and work on that thereafter).
Use .filter('#list-template') before find will solve the problem since you're trying to find the current root element in your $list_item variable that is a .box-list :
function Add2List(data, index){
var $list_item = $('#list-template').clone();
$list_item.filter('#list-template').find('.box-list').attr("id", "list_"+data.id);
$list_item.filter('#list-template').find('a.list_link').attr("href", data.link);
$list_item.filter('#list-template').find('.list_photo').attr("src", data.photo);
$('#listings_list').append($list_item.html());
console.log($list_item.html());
}
Hope this helps.
This is because your cloned object is not attached to anything. jQuery's .find runs on an object that exists.
You can do this via a preg_match but since you are templating - the best thing to use is Handlebars.

Why can't I retrieve "this" dom element without onclick?

I have a very basic question about using the "this" keyword to retrieve a DOM element.
Consider the following HTML/Javascript:
<div class="container">
<div class="regular-div">
<script type="text/javascript">
console.log(this);
</script>
Here is a div withOUT onclick
</div>
<div class="onclick-div" onclick="console.log(this)">
Here is a div with onclick
</div>
</div>
While clicking the "onclick-div" it does return the DOM object for that div. However, the console.log event calls 'this' indirectly in the "regular-div" and returns window.
Is it possible to get "this" DOM object when 'this' is called indirectly? My purpose is I want to fire a function in line in the HTML, but need to send the function "this". Here's an example of what i'm trying to do:
<div class="container">
<div class="regular-div">
<script type="text/javascript">
loadSomeHTML(this, varA, varB, varC);
</script>
</div>
</div>
Thanks everyone for any clarification of how "this" works in the above context.
In your first example, the script isn't in any way associated with the div. It's just been output within the div, but it's not connected to it. The script runs as the page is being parsed.
Is it possible to get "this" DOM object without a user interaction?
If you mean inline with the parsing of the HTML, you could do this:
<div class="container">
<div class="regular-div">
Here is a div withOUT onclick
</div>
<script type="text/javascript">
(function() {
var list = document.querySelectorAll('div');
console.log(list[list.length - 1]);
})();
</script>
</div>
Note that the script tag is immediately after the ending </div> tag for the div you're trying to target. The script gets what's currently the last div in the document as of when the script runs. Or of course you could identify the div in some way (a class, for instance) and use that (and then potentially remove it so you could do it again later in the document).
It looks dodgy, but it's perfectly valid cross-browser, and was even recommended at one stage by the Google Closure Library engineers.
Live Example:
<div class="container">
<div class="regular-div">
Here is a div withOUT onclick (look in console for result)
</div>
<script type="text/javascript">
(function() {
var list = document.querySelectorAll('div');
console.log(list[list.length - 1]);
})();
</script>
</div>
Example using a class we move:
<div class="container">
<div class="target-me">
The first div
</div>
<script type="text/javascript">
(function() {
var div = document.querySelector(".target-me");
div.classList.remove("target-me");
console.log(div);
})();
</script>
<div class="target-me">
The second div
</div>
<script type="text/javascript">
(function() {
var div = document.querySelector(".target-me");
div.classList.remove("target-me");
console.log(div);
})();
</script>
</div>
Note I didn't use id, because if we used an id and JavaScript wasn't enabled, we'd end up with an invalid document (because it would have multiple elements with the same id). It'd be fine if JavaScript were enabled (because we'd remove the id from earlier ones before later ones were created), but...
Javascript has no implicit connection to the HTML DOM. The reason why onclick works the way you want is because the HTML DOM implementation passes the element to the js callback. You need to do something similar in your other case. One way to do this is:
<div class="container">
<div class="regular-div" id="mydiv">
<script type="text/javascript">
loadSomeHTML("#mydiv", varA, varB, varC);
</script>
</div>
</div>
Then your js implementation does the lookup to find the element:
function loadSomeHTML(selector, varA, varB, varC) {
var el = document.querySelector(selector);
// now el is where you want to insert your HTML
// ...
}
The code inside the script tag doesn't have any connection with the tag itself. this should, basically, return the object on which the current function was called, or the global environment, window. In the first div, the code is just executed, on no object, so window is returned. The value of onclick, on the other hand, is treated as a function (with even some parameters, like e), that gets called on the element with the attribute. So, the code in the script element is executed in the global scope, whereas the one in the attribute is in a function scope (that's why all vars are shared across script tags).
As explained in How may I reference the script tag that loaded the currently-executing script?, the proper way of obtaining a reference to the script element whose code is being executed is
document.currentScript;
Then, to get the parent node of that element, use
document.currentScript.parentNode;
<div class="container">
<div id="regular-div">
<script type="text/javascript">
alert('#' + document.currentScript.parentNode.id);
</script>
Here is a div withOUT onclick
</div>
</div>

Swap images with a list of HTML links with JavaScript

I am trying to swap images using JavaScript. I have a main content area the loads one image. I have a sidebar with a list of links and I want to use JavaScript to change the image with each link. here is my code so far:
<html>
<head>
<title>Rat Dog Inc. ~ Services</title>
<script type="text/javascript">
var myImg;
var myImage= [];
myImage[0] = "../images/rd_surf_large.jpg";
myImage[1] = "../images/laundry.png";
myImage[2] = "../images/tug-o-war.png";
myImage[3] = "../images/cuddlepuppy.png";
myImage[4] = "../images/rd-howling.mp4";
function displayImg(){
document.getElementById('myImage[]');
}
</script>
</head>
<body>
<div id="main">
<img src="../images/rd_surf_large.png" alt="Rat Dog Inc." id="myImg"/>
</div>
<div id="sidebar">
<h2>Rat Dog Inc. Most Popular Services</h2>
<ul>
<li>Surfing Lessons <span style="font-size: 12px">(img)</span></li>
<li>Laundry Folding <span style="font-size: 12px">(img)</span></li>
<li>Tug-O-War Arm Workouts <span style="font-size: 12px">(img)</span></li>
<li>Cuddling <span style="font-size: 12px">(img)</span></li>
<li>Howling Lessons <span style="font-size: 12px">(video)</span></li>
</ul>
</div>
Ok. So here's the deal.
When you put your image on your page , like this:
<img src="image1.jpg" id="myImage">
And we assign the I'd 'myImage' to it....if we want to change the image via a link (I prefare a button), we use javascript in a way to manipulate it.
You simply use this method known as :
document.getElementById()
Which finds an element in our page by its I'd.
So if we put this button on our page:
<button onclick="changeImage()">Change The Image</button>
And put this script (which has the changeImage() function) :
<script>
function changeImage(){
var myImage = document.getElementById("myImage");
//then we change the src of the image
myImage.src="image2.jpg"
}
</script>
Our image will change of we click the button.
For reference , please visit http://www.htmldog.com/guides/javascript/intermediate/thedom
Thank you
You can use document.getElementById("image").src="image.png"; to change the src tag of an element.
Although for what you are doing, I reccomend you take a look at jQuery
please try and use this method of getElementById
For example:
<img id="image" src="image1.jpg">
<button onclick="changeToImage2('image')">Image 2</button>
<script>
function changeToImage(id) {
var myImage = document.getElementById(id);
myImage.src = "image2.jpg";
}
// then create other buttons and other functions to change the image.
</script>
Your javascript is incorrect. I'm not quite sure you understand how it works.
First of all, your function doesn't accept any parameters, and yet you're providing it with one. It will just ignore this because it doesn't know what to do with it.
Next, your document.getElementById in your displayImg() has the wrong input. Right now it's literally looking for an element with the ID "myImage[]"... of which there are none.
Also, you have a variable you never use (myImg). You should probably get rid of it.
Again, I'm getting the sense that you don't really know javascript that well or don't get the theory behind it. If you need help, w3schools has some great tutorials.

How to display JavaScript variables in a HTML page without document.write

I am trying to display some JavaScript variable on my HTML page.
I was first using document.write() but it use to overwrite the current page when the function was called.
After searching around, the general consensus was that document.write() isn't liked very much. What are the other options?
I found a page suggesting using .innerHTML but that was written in 2005.
A jsFiddle illustrating my problem http://jsfiddle.net/xHk5g/
Element.innerHTML is pretty much the way to go. Here are a few ways to use it:
HTML
<div class="results"></div>
JavaScript
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';
// Using the jQuery library
$('.results').html('Hello World!');
If you just want to update a portion of a <div> I usually just add an empty element with a class like value or one I want to replace the contents of to the main <div>. e.g.
<div class="content">Hello <span class='value'></span></div>
Then I'd use some code like this:
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';
// Using the jQuery library
$(".content .value").html("World!");
Then the HTML/DOM would now contain:
<div class="content">Hello <span class='value'>World!</span></div>
Full example. Click run snippet to try it out.
// Plain Javascript Example
var $jsName = document.querySelector('.name');
var $jsValue = document.querySelector('.jsValue');
$jsName.addEventListener('input', function(event){
$jsValue.innerHTML = $jsName.value;
}, false);
// JQuery example
var $jqName = $('.name');
var $jqValue = $('.jqValue');
$jqName.on('input', function(event){
$jqValue.html($jqName.val());
});
html {
font-family: sans-serif;
font-size: 16px;
}
h1 {
margin: 1em 0 0.25em 0;
}
input[type=text] {
padding: 0.5em;
}
.jsValue, .jqValue {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Setting HTML content example</title>
</head>
<body>
<!-- This <input> field is where I'm getting the name from -->
<label>Enter your name: <input class="name" type="text" value="World"/></label>
<!-- Plain Javascript Example -->
<h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>
<!-- jQuery Example -->
<h1>jQuery Example</h1>Hello <span class="jqValue">World</span>
</body>
</html>
You can use javascript to access elements on the page and modify their contents. So for example you might have a page with some HTML markup like so:
<div id="MyEdit">
This text will change
</div>
You can use javascript to change the content like so...
document.getElementById("MyEdit").innerHTML = "My new text!";​
Here is a working example
You can also look at using the JQuery javascript library for DOM manipulation, it has some great features to make things like this very easy.
For example, with JQuery, you could do this to acheive the same result...
$("#MyEdit").html("My new text!");
Here is a working example of the JQuery version
Based on this example you provided in your post. The following JQuery would work for you:
var x = "hello wolrd";
$("p").html(x);
Here is the working version
Using a P tag like this however is not recommended. You would ideally want to use an element with a unique ID so you can ensure you are selecting the correct one with JQuery.
there are different ways of doing this.
one way would be to write a script retrieving a command.
like so:
var name="kieran";
document.write=(name);
or we could use the default JavaScript way to print it.
var name="kieran";
document.getElementById("output").innerHTML=name;
and the html code would be:
<p id="output"></p>
i hope this helped :)
You could use jquery to get hold of the html element that you want to load the value with.
Say for instance if your page looks something like this,
<div id="FirstDiv">
<div id="SecondDiv">
...
</div>
</div>
And if your javascript (I hope) looks something as simple as this,
function somefunction(){
var somevalue = "Data to be inserted";
$("#SecondDiv").text(somevalue);
}
I hope this is what you were looking for.
If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.
​var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);​​​​​​
innerHTML is fine and still valid. Use it all the time on projects big and small. I just flipped to an open tab in my IDE and there was one right there.
document.getElementById("data-progress").innerHTML = "<img src='../images/loading.gif'/>";
Not much has changed in js + dom manipulation since 2005, other than the addition of more libraries. You can easily set other properties such as
uploadElement.style.width = "100%";
hi here is a simple example: <div id="test">content</div> and
var test = 5;
document.getElementById('test').innerHTML = test;
and you can test it here : http://jsfiddle.net/SLbKX/
Add an element to your page (such as a div) and write to that div.
HTML:
<html>
<header>
<title>Page Title</title>
</header>
<body>
<div id="myDiv"></div>
</body>
</html>
jQuery:
$('#myDiv').text('hello world!');
javascript:
document.getElementById('myDiv').innerHTML = 'hello world!';
Similar to above, but I used (this was in CSHTML):
JavaScript:
var value = "Hello World!"<br>
$('.output').html(value);
CSHTML:
<div class="output"></div>

Categories

Resources