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
Related
first time posting in here :)
I have recently started coding and for JS study practice, I wanted to make a button in my navbar that generates an object to DOM after clicking it. Can you please advise the steps regarding adding and appending items that I need to create inside addToDom function? I seem to mix up the process and after multiple failures have left the space blank.
P.S. Am I linking img correctly?
My current code so far:
const Kirstin = {
firstName: 'Kirstin',
lastName: 'Ortega',
image: "img:resources/kirstin ortega.gif",
alias: 'Police officer',
getfullName: function(){
this.firstName + ' ' + this.lastName;
},
addToDom: function(firstName, lastName, image, alias, getfullName,){
}
}
const bodyElement = document.querySelector("btn1");
bodyElement.addEventListener("click", function (){
addToDom(this.firstName, this.lastName, this.image, this.alias, this.getfullName);
});
UPDATE I am trying to replicate the same structure in HTML file as follows:
<article class = "articleTakeshi">
<div class="cardTakeshi">
<img src="resources/takeshi kovacs.gif" alt="Avatar">
<div class="container">
<h2>Takeshi Kovacs</h2>
<p>The Last Envoy</p>
</div>
</div>
</article>
So basically my goal is to create a new article with the same structure as pictured above using Javascript.
Try this:
<html>
<body>
<button id="btn1">Add</button>
<div id="list">
<article class="articleTakeshi">
<div class="cardTakeshi">
<img src="https://www.gravatar.com/avatar/6c488c6599d9a5855d7a5e5dbef2883f?s=48&d=identicon&r=PG"
alt="Avatar">
<div class="container">
<h2>Takeshi Kovacs</h2>
<p>The Last Envoy</p>
</div>
</div>
</article>
</div>
<script>
function createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
// Change this to div.childNodes to support multiple top-level nodes.
return div.firstChild;
}
const Kirstin = {
firstName: 'Kirstin',
lastName: 'Ortega',
image: "https://graph.facebook.com/10219900817020254/picture?type=large",
alias: 'Police officer',
}
const
addToDom = function ({
firstName,
lastName,
image,
alias,
getfullName
}) {
function render() {
return createElementFromHTML(`
<article class="article${firstName}">
<div class="card${firstName}">
<img src="${image}" alt="Avatar">
<div class="container">
<h2>${firstName} ${lastName}</h2>
<p>${alias}</p>
</div>
</div>
</article>
`)
}
document.querySelector("#list").appendChild(render())
}
const bodyElement = document.querySelector("#btn1");
bodyElement.addEventListener("click", function () {
addToDom(Kirstin);
});
</script>
</body>
</html>
How it works?
createElementFromHTML will create DOM element from html string.
When click the button whose id is btn1, addToDom is called with argument Kirstin which is a object.
Function addToDom will extract all fields:
firstName,
lastName,
image,
alias,
getfullName
as function local variables.
and using these variables, the render function returns a rendered html string, and we convert it to a DOM. Then we add it to the end of #list.
I am trying to print a text on the current element. I tried these two codes, but they doesn't seem to work:
This one is printing the text in the whole document:
<div>
<script>
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
document.write(data);
});
</script>
</div>
Resulting in this:
<html>
<body>
<!-- THE TEXT THAT I REQUESTED APPEARS HERE -->
</body>
</html>
And the code below is returning the following error:
<div>
<script>
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
document.this.innerHTML(data);
});
</script>
</div>
Cannot read property 'innerHTML' of undefined
Replace this with body. innerHTML is not a function its a property you need to set it.
I think you want to append to the <div> in which the <script> us present. You can access the script and get its parentNode
<div>
<script>
const script = document.scripts[document.scripts.length - 1];
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
script.parentNode.innerHTML = data;
});
</script>
</div>
Note:document.scripts[document.scripts.length - 1] will get the current <script> tag because it will be lastest script executed.
You can use document.writeln() to write within the current div
<div>
<script>
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
document.writeln(data);
});
</script>
</div>
Hre is a similar example demonstrating the result.
<div>
<script>
Promise.resolve('abc123<br>xyz789')
.then(function(data) {
document.writeln(data)
});
</script>
</div>
First you should move the script out of the div and then replace 'this' in your code with a reference to the target div.
If you give your div an id of 'target' you could do the following:
const target = document.getElementById('target');
fetch('file.txt').then((resp) => resp.text()).then((data) => target.innerHTML = data);
So in the script tag here I have an array myArr that is printed into p tag in the html:
<html>
<body>
<h1>Header 1</h1>
<div>
<p id="test"></p>
</div>
</body>
</html>
<script>
var myArr = ["abc", 123, "test"];
document.getElementById('test').innerHTML = myArr;
</script>
All that works and is good. So, I have a couple of questions about this, as I'm pretty new to javascript.
I know how to iterate through the array and print out each element within the script tag. But how would I be able to display it into the html? Is there a way to dynamically create the p tags with the element from the array as the contents?
And would I be able to easily add stying into the dynamically created p tag?
Can this kind of thing be done using something like jquery? or another popular simple javascript library?Unfortunately, I will be unable to run a full fledged javascript framework. I am only able to run a basic library.
I attempted a try here:
var my_arr = ["test", "abc", 123];
var arr_length = my_arr.length;
for (i = 0; i < arr_length; i++) {
document.createElement("p");
document.getElementById('test').innerHTML = arr_length;
my_arr[i]
}
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>
You just need to forEach over the array. Inside the callback, create a p, append it to the desired container, and set its textContent to the array element. No frameworks/libraries required:
const test = document.getElementById('test');
const my_arr = ["test", "abc", 123];
my_arr.forEach((item) => {
test.appendChild(document.createElement('p'))
.textContent = item;
});
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>
Array methods are generally preferrable to for loops, but if you really wanted to use a for loop like in your original code, you would have to set the textContent of the created p to my_arr[i], in addition to appending the p to test:
var my_arr = ["test", "abc", 123];
var arr_length = my_arr.length;
const test = document.getElementById('test');
for (i = 0; i < arr_length; i++) {
const p = document.createElement("p");
p.textContent = my_arr[i];
test.appendChild(p);
}
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>
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().
I've seen quite a few posts about zeroclipboard, but unfortunately the replies have not been helpful (understandable) to a script newbie like me. I have a page with a bunch of coupons on it. When someone clicks on a coupon, I want to copy the coupon's CODE and then take them to the coupon's LINK. I can get the CODE to copy in the alert, but I can't figure out how to then take them to the url I specify in each coupon's LINK. Can someone show me a way to do this? Here's my code...
<section style="position:relative">
<div id="sliders" style="margin:0 auto; width: auto; height:auto;">
<div class="scrollable" id="scrollable">
<div id="slider1" class="items">
<div onclick="window.open('http://url-one.com','_blank');"> <!--THERE ARE SEVERAL OF THESE-->
html...
<div id="clip_container1">
<p id="coupon1" link="url-one.com" onMouseOver="move_swf(this)">copytext1</p>
</div>
</div>
</div>
</div>
</div>
</section>
<script>
ZeroClipboard.setMoviePath( '<?= base_url("resource/js/ZeroClipboard.swf");?>' );
var clip = null;
// function $(id) { return document.getElementById(id); } //not needed?
function init()
{
clip = new ZeroClipboard.Client();
clip.setHandCursor( true );
clip.addEventListener('complete', function(client, text) {
alert("Copied Coupon Code to your clipboard:\n" + text);
// now open "link" in a new window...;
});
}
function move_swf(ee)
{
copything = document.getElementById(ee.id+"").innerHTML;
clip.setText(copything.substring(23));
if (clip.div)
{
clip.receiveEvent('mouseout', null);
clip.reposition(ee.id);
}
else{ clip.glue(ee.id);
}
clip.receiveEvent('mouseover', null);
}
window.onload = init;
</script>
Fetch the desired DOM element by the coupon code it contains
(assuming coupon codes are unique)
Add something like this below the alert code:
(assuming jquery in the lines of code I added):
clip.addEventListener('complete', function(client, text) {
alert("Copied Coupon Code to your clipboard:\n" + text);
//Add the two lines below
var mylink = jQuery( "p:contains(" + text + ")" ).attr('link');
myWhateverOpenSesameFunctionToOpenMyLink(mylink);
});