I have some JavaScript code, and if the homepage or index (e.g. at malaspulang.com) the tag <h1> does not change. But if I change the page (e.g. at malaspulang.com/lifestyle), the tag <h1> will be replaced with <h2>.
This my code:
<div id="header" class="hide"><h1>this my title</h1></div>
<script>
if(window.URL === 'malaspulang.com'){
}else{
$('#header').empty();
$('#header').html('<h2>this my title</h2>');
}
</script>
In my homepage site, the tag <h1> should replace with <h2> I think that my code is true, but I am so confused with this code. So if anyone can help me, I will be happy :)
NB: If anyone that's code with PHP, you can tell me :)
Maybe like this :
<div class="hide" id="header">
<h1>this my title</h1>
</div>
<script>
$(document).ready(function(){
console.log(document.URL);//this optional , just display your link at now
var uri= document.URL;
if(uri == 'http://malaspulang.com/'){ //use full link from your site
//do nothing , because logical true
}else{
$('#header').empty();
$('#header').html('<h2>this my title</h2>');
}
});
</script>
hope this help you
Access id using #header
$('#header').empty();
$('#header').html('<h2>this my title</h2>');
Replace $('.header') with $('#header')
$('#header') - targeting element with id attribute 'header'.
$('.header') - targeting element with class attribute 'header'.
Your problem is that your element does not have a class defined. As seen here: <div id="header"><h1>this my title</h1></div>, it has the id of 'header' not the class of header. This means that your JavaScript needs to be calling for an id of 'header' and not a class.
Here is the code that will work:
$('#header').html('<h2>This is my title</h2>');
Instead of using window.URL try to use window.location.href and also write complete url name: http://malaspulang.com
<div id="header" class="hide">
<h1>this my title</h1>
</div>
<script>
if (window.location.href === 'https://fiddle.jshell.net/_display/') { // current url
document.getElementById('header').innerHTML = "";
document.getElementById('header').innerHTML = "<h1>this my title (h1)</h1>";
}
else {
document.getElementById('header').innerHTML = "";
document.getElementById('header').innerHTML = "<h2>this my title (h2)</h2>";
}
</script>
You can also try it on jsfiddle
if($("body").hasClass("home")) {
// don't do anything.
} else{
// fire your code.
}
Use $('#header') instead of $('.header') (select by id, not by class). And you do not need $('.header').empty().
Related
I would like to rename a h1 text in the header for any single page, is it possible with a script?
The line of the title is:
Like this
I wrap in a page load event and then use the closest known selector
If you have class="titoloheader" the code is even simpler than using
div[data-row=middle] h1
If you want to change only on pages with /articoli/ you can test pathname:
const url = new URL(location.href);
if (url.pathname.split("/").indexOf("articoli") !=-1) {
document.querySelector("h1.titoloheader").innerText = "Hello"
}
})
If you want to change on page-id-X, you can do this:
Vanilla JS
const pageTitles = {
"41": "Hello",
"44": "Goodbye",
"47": "Ciao",
"3": "Arriverderci",
"313": "Hey",
"316": " Bye",
"318": " This is silly",
"50": "The end"
};
const changeHeader = () => {
let id = [...document.body.classList] // all the classes of the body tag
.filter(classStr => classStr.startsWith("page-id")); // find the one that starts with page-id
if (id.length)[, , id] = id[0].split("-") // if found (an array) grab the last part after last -
if (id && Object.keys(pageTitles).includes(id)) { // do we find that ID in the list
document.querySelector("h1.titoloheader").innerText = pageTitles[id]; // change the header
}
};
window.addEventListener("load", changeHeader); // when the page loads
<body class="home page-template-default page page-id-47 logged-in admin-bar no-customize-support ct-loading" data-link="type-1" data-forms="classic">
<div data-row="middle" data-columns="1">
<div class="ct-container">
<div data-column="middle">
<div data-items="">
<div class="ct-header-text " data-id="text">
<div class="entry-content">
<h1 class="titoloheader">Benvenuti</h1>
</div>
</div>
</div>
</div>
</div>
</div>
jQuery
const pageTitles = {
"41": "Hello",
"44": "Goodbye",
"47": "Ciao",
"3": "Arriverderci",
"313": "Hey",
"316": " Bye",
"318": " This is silly",
"50": "The end"
};
const changeHeader = () => {
let id = [...document.body.classList] // all the classes of the body tag
.filter(classStr => classStr.startsWith("page-id")); // find the one that starts with page-id
if (id.length)[, , id] = id[0].split("-") // if found (an array) grab the last part after last -
if (id && Object.keys(pageTitles).includes(id)) { // do we find that ID in the list
$("h1.titoloheader").text(pageTitles[id]); // change the header
}
};
$(document).ready(changeHeader);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body class="home page-template-default page page-id-47 logged-in admin-bar no-customize-support ct-loading" data-link="type-1" data-forms="classic">
<div data-row="middle" data-columns="1">
<div class="ct-container">
<div data-column="middle">
<div data-items="">
<div class="ct-header-text " data-id="text">
<div class="entry-content">
<h1 class="titoloheader">Benvenuti</h1>
</div>
</div>
</div>
</div>
</div>
</div>
To change the text of the h1 element in your example when the page loads, you can use:
window.addEventListener('load', event => {
const h1Element = document.querySelector("#main-container .entry-content h1");
h1Element.innerText = 'New H1 Text';
});
If you don't make the change to the H1 in the window load event callback, the element you're targeting likely won't be available in the DOM when you try to access it with document.querySelector.
jQuery:
$('#main-container div[data-row="middle"] .entry-content h1').html('Your New Title');
Vanila JS:
var el = document.querySelector("#main-container div[data-row="middle"] .entry-content h1");
el.innerHTML= "Your New Title";
Sometimes text can be replaced using pure CSS
See the collection of answers here:
How can I replace text with CSS?
Cons:
Doesn't supported by all browsers, check your requirements and
browser compatibility list.
Old text will remain hidden, can be
problem for some screen reader.
Pros:
Sometimes you cannot inject your JavaScript directly.
Here is a simple example from W3 schools
<!DOCTYPE HTML>
<html>
<body>
<h1 id="myHeader">Hello World!</h1>
<button onclick="displayResult()">Change text</button>
<script>
function displayResult() {
document.getElementById("myHeader").innerHTML = "Have a nice day!";
}
</script>
</body>
</html>
If you notice, they add a unique id to the h1 tag. This way way you can access the tag directly.
https://www.w3schools.com/tags/att_id.asp
I have a website in which I have placed specific buttons inside of articles and outside in the head/body/footer. What I plan to do is when a user clicks on the button the JavaScript code should find out if the button is located inside of an article or outside of it and send the information to my parent website using PHP's $_GET function. This is the code on the 'child' website..
<!-- Button code -->
<p id="test"></p>
<a id ="webs" href= "" onclick="jams(this);document.getElementById('test').frameBorder=0"; target="test"><button>Click me!</button> </a>
The JavaScript functions it calls.
<p id="demo"></p>
<script>
function jams(z) {
var origZ=z;
var found= false;
var sString;
while ( z.nodeName != "HTML" && !found){
var elements = z.getElementsByTagName('a');
for(var i=0; i<elements.length; i++) {
var input = elements[i] ;
sString = input.getAttribute("href");
found = sString.search(window.location.hostname) != -1;
}
z=z.parentElement;
if ( z.nodeName != "HTML" && z.nodeName != "ARTICLE"){
z=z.parentElement;
var spString = (window.location.hostname);
var link = "http://www.parentwebsite.com/one.php?id="+spString;
origZ.href = link;
}
}
var link = "http://www.parentwebsite.com/two.php?id="+sString;
origZ.href = link;
}
</script>
I have two pages on the parent website, page one.php receives the websites name (www.child.com) if the button is located outside of the article. If the button is located within an article page two.php receives the articles URL.Using PHP's $_GET Variable.
$success = $_GET["id"];
So when the user clicks the button on the webpage the button will call the jams script and it recognizes where the button is situated on the webpage and sends to either one.php the website-name OR two.php the articles URL.
The script works just fine when the button is situated within an article,
the href =
http://www.parentwebsite.com/two.php?id=http://child-articles-url.com/
BUT it fails when it is outside of an article, the href
http://www.parentwebsite.com/two.php?id=http://www.parentwebsite.com/one.php?id=http://www.child.com/
What it needs to give is just:
http://www.parentwebsite.com/one.php?id=http://www.child.com/
P.S I have used chrome's debugger while working with this.
Thanks in advance! :)
I tried to solve your problem
index.php
<!DOCTYPE html>
<html>
<head>
<title>Using JavaScript in “button” self recognition on webpage</title>
</head>
<body>
<!-- Your HTML CODE -->
<div class="aricle">
<h2> Article Starts </h2>
This is inside Article
<h2> Article Ends </h2>
</div>
<br />
This is inside Article
<!-- Your JS CODE -->
<script type="text/javascript">
function link(button) {
if (button == 1) {
//alert("button inside article");
window.location.href='http://localhost/stackTest/one.php';
} else if (button == 2) {
//alert("button outside article");
window.location.href='http://localhost/stackTest/two.php';
}
}
</script>
</body>
</html>
one.php
<h2>This is One</h2>
two.php
<h1>This is Two</h2>
Hope this helps you to identify the buttons.
and you can use the anchor (a) tags for displaying as a button instead using <button> tag inside <a>..</a> tag.
If you are using Bootstrap simply use "Button" Class for <a>.
What I am trying to achieve is if a particular page is loaded in the browser for e.g www.domain.com/page then the following piece of code should be added in the page dynamically using JS (similar to how we load the Google Analytics code)
<div id="something">
<img src="http://domain.com/images/someImage.jpg">
</div>
I am trying to figure the script which will load the above mentioned HTML code (anywhere of the page - www.domain.com/page)
Edit 1:
what I am trying to achieve is when the user goes to www.domain.com/page.html I am calling another page lets say page1.html which should contain the script which insert the HTML code I posted above. So I simply want to insert the function which should be enclosed in the tag inside page1.html. Unfortunately I can not edit www.domain.com/page.html
If you want to PLACE that code anywhere in your page using javascript, you first need to identify that PLACE in DOM Using an "id" attribute. Here's an example:
HTML:
<html>
<body>
<div id="target1"></div>
<div id="target2"></div>
</body>
</html>
JS:
var html = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
document.getElementById('target1').innerHTML = html;
document.getElementById('target2').innerHTML = html;
You can try something like this :
$(document).ready(function () {
var url = window.location.href;
$("#something").append("<img src='"+ url +"' />");
});
$(".documentholder").load("code.html");
If you a specific id of something
$(".documentholder").load("code.html #someid");
If you a specific tag and id of something
$(".documentholder").load("code.html #someid");
Here you are,
just change this part if (getFileName() == "js") with if (getFileName() == "page")
I added js because that is what is returning in the code snippet :)
function getFileName() {
var url = document.location.href;
url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
url = url.substring(url.lastIndexOf("/") + 1, url.length);
return url;
}
var div = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
if (getFileName() == "js") {
$('body').append(div);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
let's say you save this code in a html-file named something.html
$(".documentholder").load("something.html");
in this case the class "documentholder" is the container you put the code in
<html>
<head>
</head>
<body>
<div id = "start">
<h3>Start</h3>
<script>
if(Go==false)
document.write("<p>None </p>");
else
document.write("<p>Month: Day: Hour: Min: </p>");
</script>
</div>
<script>
var change = function(){
document.getElementById('start').innerHTML +=document.write("<p>NO</p>");
};
</script>
<input type = "button" value =start onClick = "change(); return false;"/>
<body>
</html>
With this it refreshes the page and I need it to be added to the div "start". Any Ideas? I have been looking up things online with fixes and none seem to work for me. I use chrome, I don't know if that will help.
Try this:
var change = function(){
document.getElementById('start').innerHTML += "<p>NO</p>";
};
This is a similar question of question on SO.
Is as to avoid of the use document.write("<p>NO</p>"); because this needs to refresh page.
Then I suggest for you use document.getElementById('start').innerHTML +="<p>NO</p>";
Or create the element!!
var p= document.createElement('P');
p.appendChild( document.createTextNode("NO") );
document.getElementById("start").appendChild(p);
Yup, what sjkm said. document.write does not return anything, it just appends whatever you give it to the end of the document. Also, your Go variable isn't declared and has no value assigned to it
I have included a file named test.php in the file index.php
lets assume index.php is like this
<html>
<head>
</head>
<body>
<h1 id="dash">Index</h1>
<div id='tab.php'>
<?php include('tab.php'); ?>
</div>
</body>
</html>
and tab.php is like this
<html>
<head>
</head>
<body>
<ul>
<li id='date' onClick="change_head(this.id);">Dates</li>
<li id='appoint' onClick="change_head(this.id);">Appointments</li>
<ul>
</body>
</html>
Here what i would like to do is, if the list item date is clicked(list items are actually tabs). The inner html of the h1 tag with id dash should be changed to Dates and if the list item appoint is clicked the inner html of same h1 tag with id dash should change to appointments.
how can i do that ?? i tried the usual javascript way by taking the ids and applying the if condition to change the innerHTML but it was not working..anyone pls help me how to do it
JAVASCRIPT (this is the js i tried to achive it...i added this in index.php)
function change_head(id){
dash = document.getElementById('dash').innerHTML;
if(id == date){
dash = "Date";
}
else if(id == appoint){
dash = "Appointment";
}
else{
dash = "Index";
}
}
You could try using jquery... something like this:
<script type="text/javascript">
$(document).ready(function () {
$("li#date").click(function () {
$("h1#dash").val("Dates");
});
$("li#appoint").click(function () {
$("h1#dash").val("Appointments");
});
});
</script>
Of course, if you had more of these tabs, I would create a single click event handler for all "li" elements and switch on the ID :-)
Assuming you're new to jquery, you'd also have to include the jquery script in your page. Something like:
<script src="/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
Check out jquery.com to get started.
If you want do it with JavaScript (i.e. without page reloading), so you need use DOM innerHTML.
Something like (if you didn't use jQuery), didn't test this code through, hope you get idea:
var changetext = function(e,t) {
e.innerHTML = t;
},
elemheader = document.getElementById('dash'),
elemdate = document.getElementById('date'),
elemappoint = document.getElementById('appoint');
if (elemdate.addEventListener) {
elemdate.addEventListener('click',changetext(elemheader,'Date'),false);
}
if (elemappoint.addEventListener) {
elemappoint.addEventListener('click',changetext(elemheader,'Appoint'),false);
}