I have written a script which should change a Link by clicking on an element. But it doesn't work. Can anyone help me out?
<!DOCTYPE html>
<html>
<h2 id="http://www.google.com" onclick="changeLink(google);" name="google">Google</h2 >
<h2 id="http://www.yahoo.com" onclick="changeLink(yahoo);" name="yahoo">Yahoo</h2 >
<h2 id="http://www.duckduckgo.com" onclick="changeLink(duckduckgo);" name="duckduckgo">DuckDuckGo</h2 >
LINK //should change the href after click on google, yahoo etc.
<script>
function changeLink(x){
document.getElementById('link').href=document.getElementsByName(x)[0].id;
}
</script>
</body>
</html>
Instead of using the string represents the name as the function argument, you're currently using undefined variables.
You have the change your HTML as such:
<h2 id="http://www.google.com" onclick="changeLink('google');" name="google">Google</h2 >
<h2 id="http://www.yahoo.com" onclick="changeLink('yahoo');" name="yahoo">Yahoo</h2 >
<h2 id="http://www.duckduckgo.com" onclick="changeLink('duckduckgo');" name="duckduckgo">DuckDuckGo</h2 >
(Mind the single quotes)
This is the most efficient way to achieve it and best performance wise by declaring a static JSON object to initialize the values.
Here is the JSFiddle Demo
//CODE
<!DOCTYPE html>
<html>
<head>
<style>
h2:hover{
color: blue;
cursor: pointer;
}
</style>
<script>
//JSON OBJECT LOADED ON DOC INIT
var sites = {
"google": "http://www.google.com",
"yahoo": "http://www.yahoo.com",
"duck": "http://www.duckduckgo.com"
};
function changeLink(site){
document.getElementById("target").href = site;
document.getElementById("target").innerHTML = site;
}
</script>
</head>
<body>
<h2 onclick="changeLink(sites.google);">Google</h2>
<h2 onclick="changeLink(sites.yahoo);">Yahoo</h2>
<h2 onclick="changeLink(sites.duck);">DuckDuckGo</h2>
http://www.example.com
</body>
</html>
Related
This question already has answers here:
onclick calling hide-div function not working
(3 answers)
Closed 1 year ago.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="overdiv">
<style>
.cross{
cursor:Default;
}
</style>
<script>
function close(){
alert("why don't you work");
}
</script>
<div id="lowerDiv">
<a class="cross" onclick=close()>x</a>
</div>
</div>
</body>
</html>
I can not understand why the x's onclick doesnt work, even if i surround the x with a div...
Any way i can fix or any other way i should be doing this? I want to close a window by pressing the x, I know how to do that but i just cant get the onclick to work... any help is appreciated.
https://stackoverflow.com/users/479156/ivar
Ivar let me know that the problem was naming the function "close()",
so i just had to name it a little different.
as explained here: onclick calling hide-div function not working
thank you Ivar!
<a class="cross" onclick=close()>x</a>
This code has a problem with onclick function. You didn't specified the function. You need the make the function code between "" tags.
Please change the code like this:
<a class="cross" onclick="close()">x</a>
I maid improvments to your code and it start to work
add "" to function in your tag onclick="onClose()",
you better add <script> in <header> but not in <body>
you can not called your function close() as it is reserved name. For example you also could not name var return etc
<!DOCTYPE html>
<html>
<head>
<script>
function onClose() {
console.log("why don't you work - I work");
}
</script>
<style>
.cross {
cursor: Default;
}
</style>
</head>
<body>
<div id="overdiv">
<div id="lowerDiv">
<a class="cross" onclick="onClose()">x</a>
</div>
</div>
</body>
</html>
If you click the button, it should have showed, but it doesn't.
Is any wrong here?
I have written many JavaScript files in this way, and tried many ways like changing the position of JavaScript code anywhere. But all the files I wrote don't work
Thanks in advance!
An instance :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debug</title>
</head>
<style>
.debug {
display : none;
}
</style>
<body>
<div class = "debug">
<p>Welcome!</p>
</div>
<button class = "show" onclick = "JavaScript : show();">Show</button>
<script type = "text/JavaScript">
function show() {
document.querySelector("debug").style.display = "flex";
}
</script>
</body>
</html>
Thanks to all of you!
About .querySelector()
The Document method querySelector() returns the first Element within the document that matches the specified selector. [...] The selector is a CSS selector string.
- MDN web docs
You should, therefore, put in your code:
document.querySelector(".debug")
You can also select HTML elements by their tags, for example, you want to select the first div:
document.querySelector("div")
document.querySelector("div").style.color = "lightgreen"
<div>Hello World</div>
Imagine you had your own HTML tag: <hello>, then you can select all hello elements with:
document.querySelector("hello")
document.querySelector("hello").style.color = "lightblue"
<hello>Hello World</hello>
Side note on inline eventListeners
Also in HTML for inline event listener instead of:
<button class = "show" onclick = "JavaScript : show();">Show</button>
you can simply write:
<button class = "show" onclick = "show();">Show</button>
It is recommended to use JavaScript to initiate these eventListeners instead of having them inline inside your HTML markup. Use the .addEventListener() method:
document.querySelector(".show").addEventListener('click', show)
↑ ↑
event function
type
Back to your code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debug</title>
</head>
<style>
.debug {
display : none;
}
</style>
<body>
<div class = "debug">
<p>Welcome!</p>
</div>
<button class ="show">Show</button>
<script type = "text/JavaScript">
document.querySelector(".show").addEventListener("click", show)
function show() {
document.querySelector(".debug").style.display = "flex";
}
</script>
</body>
</html>
Last thing
Also it's better to keep HTML, JavaScript and CSS all in separate files, for instance:
- index.html
- style.css
- script.js
And call the CSS and JavaScript files in your HTML file with the link (preferably inside <head>) and script (at the bottom of <body>) tags:
<link rel="stylesheet" type="text/css" href="style.css">
And
<script src="script.js"></script>
For class selector you need to add a dot (.) e.g. .debug
Also, in HTML, you can simply have onclick as onclick="show();"
function show() {
document.querySelector(".debug").style.display = "flex";
}
.debug {
display: none;
}
<div class="debug">
<p>Welcome!</p>
</div>
<button class="show" onclick="show();">Show</button>
You were not passing class to querySelector. Set ".debug" instead of "debug".
Below is working code:
function show() {
document.querySelector(".debug").style.display = "flex";
}
.debug {
display: none;
}
<div class="debug">
<p>Welcome!</p>
</div>
<button class="show" onclick="JavaScript : show();">Show</button>
queryselectors requires . and # for class and ID selector:
querySelector(".debug")
I cannot get my javascript to run. I have added several different options, and removed them, I have had the function in the and now moved it to the . No matter what I try the button does not work. I am trying to learn javascript. It doesn't seem that difficult to learn, but If I can't test it, what is the use? Please help!
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Change Paragraph Text</title>
</head>
<body>
<p id ="text">I’m going to change this text, I hope.</p>
<button type="button" onclick="js_style()">Click on Me</button>
<script>
function js_style() {
'use strict';
//font styles added by JS:
document.getElementById("text").style.color="purple";
document.getElementById("text").style.fontSize="18pt";
document.getElementById("text").style.fontFamily="Comic Sans MS";
}
document.getElementById("text").innerHTML = js_style();
</script>
</body>
</html>
The code you present throws undefined on the text you want to change. Simply remove
document.getElementById("text").innerHTML = js_style();
and everything should work, I suppose. Here is an example:
https://jsfiddle.net/nmLrpvhy/
The issue is that you have this line:
document.getElementById("text").innerHTML = js_style();
running automatically (because it's outside of your function) and changing the text immediately, so clicking the button does work, but it's just setting the same styles that were already set.
Additionally, innerHTML is for setting the "content" of an element, not its style. In your case, that line attempts to set the return value from the js_style function as the value for the innerHTML. But, the function doesn't return a value - - it only concerns itself with modifying styles.
Don't use inline HTML event attributes (onclick, etc.). See here for why. Instead, do all your work in JavaScript.
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Change Paragraph Text</title>
</head>
<body>
<p id ="text">I’m going to change this text, I hope.</p>
<button type="button">Click on Me</button>
<script>
// get a reference to the button
var btn = document.querySelector("[type='button']");
// set up the click event handler
btn.addEventListener("click", js_style);
function js_style() {
//font styles added by JS:
document.getElementById("text").style.color="purple";
document.getElementById("text").style.fontSize="18pt";
document.getElementById("text").style.fontFamily="Comic Sans MS";
}
</script>
</body>
</html>
here is the solution of your code:
the line in which you were trying to get your changed text was actually outside the scope of the 'js_style' function that why nothing was happening when you clink on button.
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Change Paragraph Text</title>
</head>
<body>
<p id="text">I’m going to change this text, I hope.</p>
<button type="button" onclick="js_style()">Click on Me</button>
<script>
function js_style() {
//font styles added by JS:
document.getElementById("text").style.color = "purple";
document.getElementById("text").style.fontSize = "18pt";
document.getElementById("text").style.fontFamily = "Comic Sans MS";
document.getElementById("text").innerHTML = "Changed Text"; /* this
line should be here if you want to change the text of #text in you
html */
}
/* you were written this line here which out of the scope of
function */
</script>
</body>
</html>
Can you try:
<script type="text/javascript">
instead of just
<script>
?
try with onclick="js_style">:
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Change Paragraph Text</title>
</head>
<body>
<p id ="text">I’m going to change this text, I hope.</p>
<button type="button" onclick="js_style">Click on Me</button>
<script>
function js_style() {
'use strict';
//font styles added by JS:
document.getElementById("text").style.color="purple";
document.getElementById("text").style.fontSize="18pt";
document.getElementById("text").style.fontFamily="Comic Sans MS";
}
document.getElementById("text").innerHTML = js_style();
</script>
</body>
</html>
How to execute a javaScript url when a visitor clicks inside div
Like this example :
<html>
<head>
<meta charset="UTF-8">
<style>
.youtube .play,.youtube img{cursor:pointer;position:absolute}
.youtube{position:relative;padding-bottom:56.23%;height:0;overflow:hidden;max-width:100%;background:#000;margin:5px}
.youtube embed,.youtube iframe,.youtube object{position:absolute;top:0;left:0;width:100%;height:100%;z-index:100;background:0 0}
.youtube img{bottom:0;display:block;left:0;margin:auto;max-width:100%;width:100%;right:0;top:0;border:none;height:auto;-webkit-transition:.4s all;-moz-transition:.4s all;transition:.4s all}
.youtube img:hover{-webkit-filter:brightness(75%)}
.youtube .play{height:72px;width:72px;left:50%;top:50%;margin-left:-36px;margin-top:-36px;background:url(//i.imgur.com/TxzC70f.png) no-repeat}
</style>
</head>
<body>
<div class="youtube" data-id="YQHsXMglC9A"></div>
</body>
<script>
/* Light YouTube Embeds by #labnol */
/* Web: http://labnol.org/?p=27941 */
document.addEventListener("DOMContentLoaded",
function() {
var div, n,
v = document.getElementsByClassName("youtube");
for (n = 0; n < v.length; n++) {
div = document.createElement("div");
div.setAttribute("data-id", v[n].dataset.id);
div.innerHTML = labnolThumb(v[n].dataset.id);
div.onclick = labnolIframe;
v[n].appendChild(div);
}
});
function labnolThumb(id) {
var thumb = '<img src="https://i.ytimg.com/vi/ID/hqdefault.jpg">',
play = '<div class="play"></div>';
return thumb.replace("ID", id) + play;
}
function labnolIframe() {
var iframe = document.createElement("script");
iframe.setAttribute("src", "https://www.youtube.com/embed/" + this.dataset.id + "?autoplay=1");
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "1");
this.parentNode.replaceChild(iframe, this);
}
</script>
</html>
Like this picture
image
.
Html code + javascript :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="a" style="background-color:#999; height:90px; width:250px;" >Click here</div>
</body>
</html>
Javascript :
<script type="text/javascript">
document.write("Hello World!");
</script>
Or :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
How do I run javaScript url when a visitor clicks inside div ?
Something liked this would do it...
function clickMe() {
alert("You clicked me!")
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="a" style="background-color:#999; height:90px; width:250px;" onclick="clickMe()" >Click here</a></div>
</body>
</html>
First of all, instead of trying to run a script, you should try to run a function.
For example
function test(){
document.write("Hello World!")
}
function test2(){
document.getElementById("output").innerHTML = "Hello World!"
}
<div onclick="test()">
<p> Click me </p>
</div>
<div onclick="test2()">
<p> Click me (won't remove screen) </p>
</div>
<div id="output">
</div>
Clicking on the first div will call the test() function. This function will however overwrite everything on the screen, that's not what you want.
The second method doesn't do that, instead it sets the content of the third div to "Hello World!"
I believe you want to run a JavaScript function when your div gets clicked. You just need to add an onclick() event to your <div> tag and declare that function. So your div would be something like this:
<div id="a" style="background-color:#999; height:90px; width:250px;" onclick="writeFunction();">Click here</div>
And the function, with the same name as you declared on your onclick:
<script type="text/javascript">
function writeFunction(){
document.write("Hello World!");
}
</script>
As you have used document.write and i have kept that, it does not show the result that you have illustrated in your picture and your div is vanishing. In order to do as you have imagined, you have to add a <p> element which is initally blank:
<p id='text'></p>
and then ask your function to set its text, like this:
document.getElementById('text').innerHTML = "Hello World!";
You can learn more here: https://www.w3schools.com/jsref/event_onclick.asp
How to get full url which starts url with http://sin1.g.adnxs.com
here is my code
<div id="testingurl">
<div class="ads98E6LYS20621080">
<!-- we are getting this script dynamically -->
<iframe src="http://testing.com">
if the anchor link start with http://sin1.g.adnxs.com then alert
</iframe>
<!-- we are getting this script dynamically -->
</div>
</div>
if(window.location.origin == 'http://sin1.g.adnxs.com'){
alert('some alert');
}
Use this logic
$( document ).ready(function() {
if (window.location.href.startsWith('http://sin1.g.adnxs.com')){
alert('Your message') ;
}
});
Are you looking something like this:
if (window.location.href.indexOf("http://www.sin1.g.adnxs.com") > -1) {
alert(window.location.href);
}
As other suggested, you can use window.location.origin in order to get that url
Example:
if(window.location.origin === 'http://sin1.g.adnxs.com'){
alert('alert');
}
Generally you can use window.location for:
window.location.href returns the href (URL) of the current page
window.location.hostname returns the domain name of the web host
window.location.pathname returns the path and filename of current page
window.location.protocol returns the web protocol used (http:// or https://)
window.location.assign loads a new document
More info can be found here:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location
EDIT:
Please have a look at the following example.
In case you have two web pages, parent.html and content.html and content.html is
displayed within parent.html using an iframe.
If you want check the URL of parent.html within content.html you can use the following script:
-------------------------- parent.html
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style>
</style>
<script>
window.name = 'parent';
</script>
</head>
<body>
PARENT
<iframe src="content.html" width="200" height="200"></iframe>
</body>
</html>
-------------------------- content.html
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style>
body {
background-color: red;
}
</style>
<script>
app = {
start: function () {
window.name = 'content';
var parent = window.parent;
console.log(parent.name);
if (parent.location.origin === 'http://sin1.g.adnxs.com') {
alert('alert');
}
}
};
</script>
</head>
<body onload="app.start();">
CONTENT
</body>
</html>