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);
});
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 been struggling with this so hopefully someone can help!
So I am looking to change the inner html of a paragraph to another html element containing a div and script when my frame receives a message from the page code. I have this working only for when the inner html is set to replace with a normal string
like this
document.getElementById('demo').innerHTML = "testing" ;
the correct replacement shows up here
<p id="demo">testing</p>
but when I try and pass in the other html to replace that section like this:
document.getElementById('demo').innerHTML =
'<div id="tlkio" data-channel="regerhtrh" data-theme="theme--night" style="width:100%;height:400px;"></div><script async src="https://tlk.io/embed.js" type="text/javascript"></script>';
it does not work. I don't think it is a quotation issue because I wrapped the outsides of it with single quotes. not sure what else to try. Below is the full html and I would appreciate any help!
<!doctype html>
<html>
<head>
<script type="text/javascript">
function init () {
// when a message is received from the page code
window.onmessage = (event) => {
if (event.data) {
console.log("HTML Code Element received a message!");
insertMessage(event.data);
}
}
}
// display received message
function insertMessage(msg) {
document.getElementById('demo').innerHTML =
'<div id="tlkio" data-channel="regerhtrh" data-theme="theme--night" style="width:100%;height:400px;"></div><script async src="https://tlk.io/embed.js" type="text/javascript"></script>'
;
}
</script>
</head>
<body onload="init();" style="background-color:lightgray;">
<h1>HTML Component Test</h1>
<p id="demo">
should put html here
</p>
</body>
</html>
The major issue is the </script> closing tag in your code. It closes YOUR block, not the block you are inserting.
You have to do so:
var myHtml = "<div id='tlkio' data-channel='regerhtrh' data-theme='theme--night' style='width: 100%; height:400px;'></div><script async src='https://tlk.io/embed.js' type='text/javascript'></scr"+"ipt>";
Second, script you insert with innerHTML wont run. Use document.createElement('script') instead
UPDATE
Here is the jsFiddle: https://jsfiddle.net/ArtyomShegeda/62fdybc0/21/
You may consider swapping the Quotes used:
function insertMessage(msg) {
var myHtml = "<div id='tlkio' data-channel='regerhtrh' data-theme='theme--night' style='width: 100%; height:400px;'></div><script async src='https://tlk.io/embed.js' type='text/javascript'></script>";
document.getElementById('demo').innerHTML = myHtml;
}
This may add it, yet may not render it. You might consider creating the elements and appending them.
function insertMessage(msg) {
var tlkio = document.createElement("div");
tlkio.style.width = "100%";
tlkio.style.width = "400px";
tlkio.setAttribute('data-channel', 'regerhtrh');
tlkio.setAttribute('data-theme', 'theme--night');
var tlkScript = document.createElement("script");
tlkScript.src = 'https://tlk.io/embed.js';
tlkScript.type = 'text/javascript';
tlkScript.async = true;
document.getElementById('demo').append(tlkio, tlkScript);
}
Based on some research here: load scripts asynchronously, it may be best to append the script to the <head>.
Hope that helps.
Update 1
Per your fiddle, once updated, it is working as you suggested: https://jsfiddle.net/Twisty/62fdybc0/7/
The following is added to #myDIV element:
<div style="width: 100%; height: 400px;" data-channel="regerhtrh" data-theme="theme--night"></div><script src="https://tlk.io/embed.js" type="text/javascript" async="async"></script>
I am very new to coding and am trying to create an app for a study. I am having trouble displaying an element on the correct page of my app using cordova and Xcode. Basically, I want to display a clickable phone number at the end of my app and I am having trouble getting the element to show only on that page (and not on every page of the app). I have figured out how to hide the element, but now I can't get it to appear in the right place. Here is my html code:
<script>
function show(shown, hidden) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden).style.display='none';
return false;
}
</script>
</head>
<body>
<!-- HTML Template -->
<body onload="app.initialize()">
<div class="app">
<div id="window">
<div id="question">
</div>
<div id="popup" style="display:none">
Please call any of the below:
Phone System: 800-555-5555
</div>
</body>
</html>
I tried to include the following in my .js file but it did not work:
var $prehashval = "";
function loop()
{
if (location.hash.slice(1)!=$prehashval)
hashChanged();
$prehashval = location.hash.slice(1);
setTimeout("loop()", 100);
}
function hashChanged()
{
var $output;
switch (location.hash.slice(1))
{
case "question":
document.getElementById('question').style.display = "";
document.getElementById('popup').style.display = "none";
break;
case "popup":
document.getElementById('question').style.display = "none";
document.getElementById('popup').style.display = "";
break;
default:
$output = location.hash.slice(1);
}
}
loop();
I also tried adding the following:
$("#popup").hide()
$("#popup").display()
With no luck. Would appreciate any advice! Thank you.
With the help of some friends, I have fixed this problem! I added the following code to the .js file:
if (question.variableName === 'popup') {
$('#popup').show();
Hope this helps someone in the future!
I have an ERB document:
<!DOCTYPE html>
<html>
<head>
<script>
scrollDown = function() {
document.body.scrollTop = document.body.scrollHeight;
}
</script>
</head>
<body onload='scrollDown()'>
<div id='2'>
</div>
<div id='target'>
<%=#chat%> <!-- #chat is a variable from my ruby file -->
</div>
<form action="/addChat?n=<%=#name%>" method='post'>
<input name='nchat' type='text' onload='this.focus' autofill='no' style='width:100%;height:10em;vertical-align:top'>
<input type='submit'>
</form>
<a href='/home'>Go home!</a>
</body>
</html>
And I would like to have it so that every half of a second it will do two things. First it needs to move the contents of the <div id="target"> to <div id="2"> then reload the contents of <div id="target"> getting the variable #chat from another route (post \content do ... end).
I am using sinatra and heroku. PLEASE DO NOT ANSWER USING JQUERY. I DO NOT KNOW HOW TO USE JQUERY AND I WOULD LIKE TO UNDERSTAND HOW THE ANSWER WORKS.
I will be happy to add any resources you need to answer this question, and I will try to do so as promptly as possible.
Clarification
Here is my code which has been slightly modified since asking this question (I hope this code clarifies my question). When I enter the loop to move things from <div id="target"> to <div id="2"> into the console in browser (google chrome latest version) it runs fine and moves everything correctly. Here is the loop:
while (document.getElementById('target').childNodes.length > 0) {
document.getElementById("2").appendChild(document.getElementById('target').childNodes[0]);
}
Now my only remaining issue is reloading the content of <div id="target"> from the route in my app file post '/chatContent' do ... return #chat end where #chat is a dynamically changing variable every 0.5 seconds and before reloading each time running the above loop. Here is my current attempt at the reloading with the loop (also most of this is copy paste from various sources, so I don't really understand it):
var refreshDelay = 5000000;
function createRequestObject() {
var ro;
if(navigator.appName == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq() {
while (document.getElementById('target').childNodes.length > 0) {
document.getElementById("2").appendChild(document.getElementById('target').childNodes[0]);
}
http.open('post', '/chatContent?n=<%=#name%>');
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
while (document.getElementById('target').childNodes.length > 0) {
document.getElementById("2").appendChild(document.getElementById('target').childNodes[0]);
}
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('target').innerHTML = response;
setTimeout(sndReq, refreshDelay);
}
}
setTimeout(sndReq, refreshDelay);
</script>
<script>
scrollDown = function() {
document.body.scrollTop = document.body.scrollHeight;
}
function movethings() {
while (document.getElementById('target').childNodes.length > 0) {
document.getElementById("2").appendChild(document.getElementById('target').childNodes[0]);
}
}
Just to clarify, what I am looking for is a replacement for the above code, including 1st) Running the loop to move the contents of <div id="target"> to <div id="2"> then 2nd) reloading <div id='target'>. The order is important.
I hope that this clarification has narrowed the scope of my question. If it has not, please leave a comment about why it is too broad because I do not understand how it is.
Edit 2
In summary, each answer must, in order, do the following:
Move content of <div id="target"> to <div id="2">
Reload <div id="target"> so that it contains the return of my Sinatra route, post "/chatContent"
I have a image with link
<div id="img"><img src="/src/img.png"/></div>
but i don't wanna use tag for linking.the page has multiple entries like this in a page as it is being populated for a search result.Some 10 or more entries will be there in a page.its all inside a <div id="result"></div>
have an idea for doing it dojo.help me finish that
function(){
dojo.query('.Result').forEach(function(item){
try{
var href = dojo.query('.img',item)[0]
//do things
dojo.connect(Node,'onclick',dojo.hitch(this,function(){
window.location = location;
}));
Try the code below:
<div id="result">
<div class="imageContainer"><img location="src/blah.html" src="/src/img.png"></div>
</div>
dojo.query("#result .imageContainer img").connect("onclick", function() {
var location = dojo.attr(this, "location");
if (location) {
window.location.href = location;
}
});