I have a javascript which opens up a window just before a surfer enters my site which has 24 hours cookie meaning it will popup again after the surfer visits my site again after 24 hours.
Right now one can only close the div if the red "x" button is pressed. Also when I run it I can only add images or iframes but I'd like o add some text like "welcome to my site".
Here is the code
var floatingAd={
run: function (e, t) {
if (e === 2 || e === 1 && (this.getCookie("floatingAd") === null || this.getCookie("floatingAd") === "")) {
document.write('<div id="floatingAdFixed" style="bottom: 0px; background: #fff; font-family: Arial, Helvetica, sans-serif; left: 0; padding: 0px 0; position: fixed; font-size: 16px; width: 100%; z-index: 99999; float: left; vertical-align: middle; margin: 0px 0 0; opacity: 0.88; font-weight: bold;">');
document.write('<div style="text-align: right; width: 710px; margin: 340px auto;"><img onclick="floatingAd.close(' + e + ');" style="position: absolute; margin-top: -11px; margin-left: -23px; cursor: pointer;" src="data:image/png;base64,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"></div>');
document.write('<div id="floatingAd" style="text-align: center; width: 710px; margin: 300px auto; ">');
document.write("</div>");
document.write("</div>");
document.getElementById("floatingAd").innerHTML = t
}
},
close: function (e) {
if (e === 1) {
this.setCookie("floatingAd", 1, 1)
}
document.getElementById("floatingAdFixed").style.display = "none"
},
setCookie: function (t, n, r) {
var i = new Date;
i.setDate(i.getDate() + r);
var s = escape(n) + (r == null ? "" : "; expires=" + i.toUTCString());
document.cookie = t + "=" + s + ";path=/"
},
getCookie: function (e) {
var t = document.cookie;
var n = t.indexOf(" " + e + "=");
if (n == -1) {
n = t.indexOf(e + "=")
}
if (n == -1) {
t = null
} else {
n = t.indexOf("=", n) + 1;
var r = t.indexOf(";", n);
if (r == -1) {
r = t.length
}
t = unescape(t.substring(n, r))
}
return t
}
}
/**
* Run the script
* 1 = 24 hours cookie, 2 = refresh
*/
floatingAd.run(1, '');
Two questions:
How do I make it to close if you click anywhere on the screen?
Hwo do I make it to show text in the floatingAd.run(1, '');?
For 1 check out How do I detect a click outside an element?
EDIT: If you would like to have the window closed if "you click anywhere on the screen", just use your object in the following way:
$('html').click(function() {
// You may skip the following if statement, it may work without it
if (document.getElementById("floatingAdFixed").style.display != "none")
// The following line is what you'll definitely need
floatingAd.close(1);
});
For 2, just add it as another variable in run like this
var floatingAd={
run: function (e, t, text) {
// ...
document.write('<div id="textContainer">' + text + '</div>');
// ...
}
Then use it like this:
floatingAd.run(1, '', 'Writing some text');
DEMO HERE
Related
I have this code, it should work well, but it doesn't and I can't find out why. I also should mention that this does use the prismjs library. I customized it to let my created HTML element of codeform to be used like the pre element in the library.
The prismjs library has no role in the problem, it is just a syntex highlighter used to format the output.
function codeform123() {
var cod = document.querySelectorAll("codeform");
for (let i=0; i < cod.length; i++) {
var type = cod[i].getAttribute("type");
var content = cod[i].innerHTML.split(/\n/||/\r/||/\n\r/||/\r\n/);
cod[i].innerHTML = "";
for (let ii=0; ii < content.length; ii++) {
if (content[ii] != "") {
var thisLine = content[ii].split("");
const splited = [];
var splitedNum = 0;
var sa = 0;
var sb = 1;
var back = 0;
var iii;
for (iii=0; iii<thisLine.length; iii++) {
if (thisLine[iii] == "undefined" || thisLine[iii] == undefined || thisLine[iii] == null) {continue;}
if (thisLine[iii] == " " && back == 0) {
splited[sa+splitedNum] += thisLine[iii];
} else {
if (thisLine[iii] != " " || thisLine[iii+1] != " ") {
back = 1;
if (iii==0) {
sa=1;
sb=0;
}
splited[sb+splitedNum] += thisLine[iii];
} else {
splitedNum+=2;
splited[sa+splitedNum] += thisLine[iii];
back = 0;
}
}
}
for (iii=0; iii<splited.length; iii++) {
if (splited[iii].includes(" ")) {
cod[i].innerHTML += splited[iii];
} else {
var code = document.createElement("code");
code.classList = "language-"+type;
code.innerHTML = splited[iii];
cod[i].appendChild(code);
}
}
if (ii != (content.length-1)) {cod[i].innerHTML += "\n"||"\r"||"\n\r"||"\r\n";}
} else {
if (ii != (content.length-1)) {cod[i].innerHTML += "\n"||"\r"||"\n\r"||"\r\n";}
}
}
}
}
codeform123();
codeform {
display: block;
color: #f8f8f2;
background: #272822;
margin: 1em 0;
padding: 4px;
border-radius: 8px;
text-shadow: 0 1px rgba(0, 0, 0, 0.3);
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
<codeform type="css">#test {
width: 1px;
height: 1px;
}</codeform>
As you can see in the code snippet above, it is returning this:
undefined#test {
undefined undefinedwidth: 1px;
undefined undefinedheight: 1px;
undefined}
However, I would like it to return this:
#test {
width: 1px;
height: 1px;
}
So, how do I get it to work the way that I want? As I don't understand where the undefineds come from. I believe the problem is when the strings are reconstructed into the array splited. As I have looked at the thisLine array and have seen that there are no undefineds, so where do they come from?
It should be noted that I have tried using .slice() and yes it did work when I placed them where the strings are added back to the codeform element. When I did add them, the code snippet would look like this:
function codeform123() {
var cod = document.querySelectorAll("codeform");
for (let i=0; i < cod.length; i++) {
var type = cod[i].getAttribute("type");
var content = cod[i].innerHTML.split(/\n/||/\r/||/\n\r/||/\r\n/);
cod[i].innerHTML = "";
for (let ii=0; ii < content.length; ii++) {
if (content[ii] != "") {
var thisLine = content[ii].split("");
const splited = [];
var splitedNum = 0;
var sa = 0;
var sb = 1;
var back = 0;
var iii;
for (iii=0; iii<thisLine.length; iii++) {
if (thisLine[iii] == "undefined" || thisLine[iii] == undefined || thisLine[iii] == null) {continue;}
if (thisLine[iii] == " " && back == 0) {
splited[sa+splitedNum] += thisLine[iii];
} else {
if (thisLine[iii] != " " || thisLine[iii+1] != " ") {
back = 1;
if (iii==0) {
sa=1;
sb=0;
}
splited[sb+splitedNum] += thisLine[iii];
} else {
splitedNum+=2;
splited[sa+splitedNum] += thisLine[iii];
back = 0;
}
}
}
for (iii=0; iii<splited.length; iii++) {
if (splited[iii].includes(" ")) {
cod[i].innerHTML += splited[iii].slice(9);
} else {
var code = document.createElement("code");
code.classList = "language-"+type;
code.innerHTML = splited[iii].slice(9);
cod[i].appendChild(code);
}
}
if (ii != (content.length-1)) {cod[i].innerHTML += "\n"||"\r"||"\n\r"||"\r\n";}
} else {
if (ii != (content.length-1)) {cod[i].innerHTML += "\n"||"\r"||"\n\r"||"\r\n";}
}
}
}
}
codeform123();
codeform {
display: block;
color: #f8f8f2;
background: #272822;
margin: 1em 0;
padding: 4px;
border-radius: 8px;
text-shadow: 0 1px rgba(0, 0, 0, 0.3);
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
<codeform type="css">#test {
width: 1px;
height: 1px;
}</codeform>
In this second code snippet, it does what I want, but I am wondering if there is a better way to do it, meaning fixing the problem without using .slice() right before the string is added back into the codeform element.
Your code is very hard to follow, but I suspect that the splitedNum += 2 line is the problem because it risks creating an array with holes, and the holes will end up showing up as undefined. But I can't say I understand what your code is doing.
There is also several problems in your code, for instance:
cod[i].innerHTML.split(/\n/||/\r/||/\n\r/||/\r\n/)
and
cod[i].innerHTML += "\n"||"\r"||"\n\r"||"\r\n";
do not do what you think they do.
if (content != "")
is always true as content is an array.
if (thisLine[iii] == "undefined" || thisLine[iii] == undefined || thisLine[iii] == null)
All those make no sense because thisLine[iii] is a one-character string.
The javascript code for cookie acceptance is ok but not working, instead I find this console error :
The use of drawWindow method of CanvasRenderingContext2D is deprecated. Use the tabs.captureTab API for extensions instead https://developer.mozilla.org/fr/docs/Mozilla/Add-ons/WebExtensions/API/tabs/captureTab pagedata-script.js:1:12465
I don't know where or why it comes from but my javascript code does not run.
If someone has an idea.
Here is the code below :
HTML
<div id="consent-popup" class="hidden dark">
<img src="_images/cookie.png"/>
<p>By using this site, you agree to our Terms of Service.<br>
Please <a id="accept" href="#">Accept</a> before using the site.
</p>
</div>
CSS
#consent-popup {
position: fixed;
display: inline-flex;
bottom: 3.5rem;
right: 0;
padding: 25px 5% 25px 25px;
width: 40vw;
box-shadow: -2px 5px 10px 5px #19233e;
background-color: #FFFFFF;
transition: all 1s ease;
}
#consent-popup.hidden {
transform: translate(100%, 0);
opacity: 0;
}
#consent-popup > img {
margin: 0 25px 0 0;
width: 50px;
height: 50px;
}
#consent-popup > p {
margin: 0;
font-family: ArialLight;
font-size: 1rem;
color: #000000;
text-align: left;
}
#consent-popup > p > a {
color: #dbdce8;
}
Javascript
//accept_cookies.js
function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function setCookie(cname, cvalue, exdays){
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/;SameSite=None;secure=" + true + ";";
}
function isAccept(cname){
//console.log(getCookie(cname));
if(getCookie(cname) == "true"){
return true;
}
else{
return false;
}
}
window.onload = () => {
function acceptFn(){
setCookie("abc_consent", true, 7);
consentPopup.classList.add('hidden');
}
const consentPopup = document.getElementById('consent-popup');
const acceptBtn = document.getElementById('accept');
acceptBtn.addEventListener('click', acceptFn);
if (!isAccept("bdc_consent")) {
setTimeout(() => {
consentPopup.classList.remove('hidden');
}, 2000);
}
};
The only external scripts are those of bootstrap and ajax googleapis:
"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"
"https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"
Thanks.
There was a conflict with another javascript function in another file that used the window.onload = () => {} function
to create an animation.
So I remove it.
The requirement is to sow the information continuously hence opted for a ticker style.
Now I am using an [ticker-style.css] along with [jquery.ticker.js]
It works fine in a Full Screen however while browsing in a Mobile/Tabler - the text is getting cut (see below screenshot) - I tried to play around the width however the rendering was not as expected.
Can you help here.
Thanks in advance.
/*
jQuery News Ticker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2 of the License.
jQuery News Ticker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with jQuery News Ticker. If not, see <http://www.gnu.org/licenses/>.
*/
(function($){
$.fn.ticker = function(options) {
// Extend our default options with those provided.
// Note that the first arg to extend is an empty object -
// this is to keep from overriding our "defaults" object.
var opts = $.extend({}, $.fn.ticker.defaults, options);
// check that the passed element is actually in the DOM
if ($(this).length == 0) {
if (window.console && window.console.log) {
window.console.log('Element does not exist in DOM!');
}
else {
alert('Element does not exist in DOM!');
}
return false;
}
/* Get the id of the UL to get our news content from */
var newsID = '#' + $(this).attr('id');
/* Get the tag type - we will check this later to makde sure it is a UL tag */
var tagType = $(this).get(0).tagName;
return this.each(function() {
// get a unique id for this ticker
var uniqID = getUniqID();
/* Internal vars */
var settings = {
position: 0,
time: 0,
distance: 0,
newsArr: {},
play: true,
paused: false,
contentLoaded: false,
dom: {
contentID: '#ticker-content-' + uniqID,
titleID: '#ticker-title-' + uniqID,
titleElem: '#ticker-title-' + uniqID + ' SPAN',
tickerID : '#ticker-' + uniqID,
wrapperID: '#ticker-wrapper-' + uniqID,
revealID: '#ticker-swipe-' + uniqID,
revealElem: '#ticker-swipe-' + uniqID + ' SPAN',
controlsID: '#ticker-controls-' + uniqID,
prevID: '#prev-' + uniqID,
nextID: '#next-' + uniqID,
playPauseID: '#play-pause-' + uniqID
}
};
// if we are not using a UL, display an error message and stop any further execution
if (tagType != 'UL' && tagType != 'OL' && opts.htmlFeed === true) {
debugError('Cannot use <' + tagType.toLowerCase() + '> type of element for this plugin - must of type <ul> or <ol>');
return false;
}
// set the ticker direction
opts.direction == 'rtl' ? opts.direction = 'right' : opts.direction = 'left';
// lets go...
initialisePage();
/* Function to get the size of an Object*/
function countSize(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
function getUniqID() {
var newDate = new Date;
return newDate.getTime();
}
/* Function for handling debug and error messages */
function debugError(obj) {
if (opts.debugMode) {
if (window.console && window.console.log) {
window.console.log(obj);
}
else {
alert(obj);
}
}
}
/* Function to setup the page */
function initialisePage() {
// process the content for this ticker
processContent();
// add our HTML structure for the ticker to the DOM
$(newsID).wrap('<div id="' + settings.dom.wrapperID.replace('#', '') + '"></div>');
// remove any current content inside this ticker
$(settings.dom.wrapperID).children().remove();
$(settings.dom.wrapperID).append('<div id="' + settings.dom.tickerID.replace('#', '') + '" class="ticker"><div id="' + settings.dom.titleID.replace('#', '') + '" class="ticker-title"><span><!-- --></span></div><p id="' + settings.dom.contentID.replace('#', '') + '" class="ticker-content"></p><div id="' + settings.dom.revealID.replace('#', '') + '" class="ticker-swipe"><span><!-- --></span></div></div>');
$(settings.dom.wrapperID).removeClass('no-js').addClass('ticker-wrapper has-js ' + opts.direction);
// hide the ticker
$(settings.dom.tickerElem + ',' + settings.dom.contentID).hide();
// add the controls to the DOM if required
if (opts.controls) {
// add related events - set functions to run on given event
$(settings.dom.controlsID).on('click mouseover mousedown mouseout mouseup', function (e) {
var button = e.target.id;
if (e.type == 'click') {
switch (button) {
case settings.dom.prevID.replace('#', ''):
// show previous item
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
manualChangeContent('prev');
break;
case settings.dom.nextID.replace('#', ''):
// show next item
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
manualChangeContent('next');
break;
case settings.dom.playPauseID.replace('#', ''):
// play or pause the ticker
if (settings.play == true) {
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
pauseTicker();
}
else {
settings.paused = false;
$(settings.dom.playPauseID).removeClass('paused');
restartTicker();
}
break;
}
}
else if (e.type == 'mouseover' && $('#' + button).hasClass('controls')) {
$('#' + button).addClass('over');
}
else if (e.type == 'mousedown' && $('#' + button).hasClass('controls')) {
$('#' + button).addClass('down');
}
else if (e.type == 'mouseup' && $('#' + button).hasClass('controls')) {
$('#' + button).removeClass('down');
}
else if (e.type == 'mouseout' && $('#' + button).hasClass('controls')) {
$('#' + button).removeClass('over');
}
});
// add controls HTML to DOM
$(settings.dom.wrapperID).append('<ul id="' + settings.dom.controlsID.replace('#', '') + '" class="ticker-controls"><li id="' + settings.dom.playPauseID.replace('#', '') + '" class="jnt-play-pause controls"><!-- --></li><li id="' + settings.dom.prevID.replace('#', '') + '" class="jnt-prev controls"><!-- --></li><li id="' + settings.dom.nextID.replace('#', '') + '" class="jnt-next controls"><!-- --></li></ul>');
}
if (opts.displayType != 'fade') {
// add mouse over on the content
$(settings.dom.contentID).mouseover(function () {
if (settings.paused == false) {
pauseTicker();
}
}).mouseout(function () {
if (settings.paused == false) {
restartTicker();
}
});
}
// we may have to wait for the ajax call to finish here
if (!opts.ajaxFeed) {
setupContentAndTriggerDisplay();
}
}
/* Start to process the content for this ticker */
function processContent() {
// check to see if we need to load content
if (settings.contentLoaded == false) {
// construct content
if (opts.ajaxFeed) {
if (opts.feedType == 'xml') {
$.ajax({
url: opts.feedUrl,
cache: false,
dataType: opts.feedType,
async: true,
success: function(data){
count = 0;
// get the 'root' node
for (var a = 0; a < data.childNodes.length; a++) {
if (data.childNodes[a].nodeName == 'rss') {
xmlContent = data.childNodes[a];
}
}
// find the channel node
for (var i = 0; i < xmlContent.childNodes.length; i++) {
if (xmlContent.childNodes[i].nodeName == 'channel') {
xmlChannel = xmlContent.childNodes[i];
}
}
// for each item create a link and add the article title as the link text
for (var x = 0; x < xmlChannel.childNodes.length; x++) {
if (xmlChannel.childNodes[x].nodeName == 'item') {
xmlItems = xmlChannel.childNodes[x];
var title, link = false;
for (var y = 0; y < xmlItems.childNodes.length; y++) {
if (xmlItems.childNodes[y].nodeName == 'title') {
title = xmlItems.childNodes[y].lastChild.nodeValue;
}
else if (xmlItems.childNodes[y].nodeName == 'link') {
link = xmlItems.childNodes[y].lastChild.nodeValue;
}
if ((title !== false && title != '') && link !== false) {
settings.newsArr['item-' + count] = { type: opts.titleText, content: '' + title + '' }; count++; title = false; link = false;
}
}
}
}
// quick check here to see if we actually have any content - log error if not
if (countSize(settings.newsArr < 1)) {
debugError('Couldn\'t find any content from the XML feed for the ticker to use!');
return false;
}
settings.contentLoaded = true;
setupContentAndTriggerDisplay();
}
});
}
else {
debugError('Code Me!');
}
}
else if (opts.htmlFeed) {
if($(newsID + ' LI').length > 0) {
$(newsID + ' LI').each(function (i) {
// maybe this could be one whole object and not an array of objects?
settings.newsArr['item-' + i] = { type: opts.titleText, content: $(this).html()};
});
}
else {
debugError('Couldn\'t find HTML any content for the ticker to use!');
return false;
}
}
else {
debugError('The ticker is set to not use any types of content! Check the settings for the ticker.');
return false;
}
}
}
function setupContentAndTriggerDisplay() {
settings.contentLoaded = true;
// update the ticker content with the correct item
// insert news content into DOM
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
// set the next content item to be used - loop round if we are at the end of the content
if (settings.position == (countSize(settings.newsArr) -1)) {
settings.position = 0;
}
else {
settings.position++;
}
// get the values of content and set the time of the reveal (so all reveals have the same speed regardless of content size)
distance = $(settings.dom.contentID).width();
time = distance / opts.speed;
// start the ticker animation
revealContent();
}
// slide back cover or fade in content
function revealContent() {
$(settings.dom.contentID).css('opacity', '1');
if(settings.play) {
// get the width of the title element to offset the content and reveal
var offset = $(settings.dom.titleID).width() + 20;
$(settings.dom.revealID).css(opts.direction, offset + 'px');
// show the reveal element and start the animation
if (opts.displayType == 'fade') {
// fade in effect ticker
$(settings.dom.revealID).hide(0, function () {
$(settings.dom.contentID).css(opts.direction, offset + 'px').fadeIn(opts.fadeInSpeed, postReveal);
});
}
else if (opts.displayType == 'scroll') {
// to code
}
else {
// default bbc scroll effect
$(settings.dom.revealElem).show(0, function () {
$(settings.dom.contentID).css(opts.direction, offset + 'px').show();
// set our animation direction
animationAction = opts.direction == 'right' ? { marginRight: distance + 'px'} : { marginLeft: distance + 'px' };
$(settings.dom.revealID).css('margin-' + opts.direction, '0px').delay(20).animate(animationAction, time, 'linear', postReveal);
});
}
}
else {
return false;
}
};
// here we hide the current content and reset the ticker elements to a default state ready for the next ticker item
function postReveal() {
if(settings.play) {
// we have to separately fade the content out here to get around an IE bug - needs further investigation
$(settings.dom.contentID).delay(opts.pauseOnItems).fadeOut(opts.fadeOutSpeed);
// deal with the rest of the content, prepare the DOM and trigger the next ticker
if (opts.displayType == 'fade') {
$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
$(settings.dom.wrapperID)
.find(settings.dom.revealElem + ',' + settings.dom.contentID)
.hide()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.show()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.removeAttr('style');
setupContentAndTriggerDisplay();
});
}
else {
$(settings.dom.revealID).hide(0, function () {
$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
$(settings.dom.wrapperID)
.find(settings.dom.revealElem + ',' + settings.dom.contentID)
.hide()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.show()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.removeAttr('style');
setupContentAndTriggerDisplay();
});
});
}
}
else {
$(settings.dom.revealElem).hide();
}
}
// pause ticker
function pauseTicker() {
settings.play = false;
// stop animation and show content - must pass "true, true" to the stop function, or we can get some funky behaviour
$(settings.dom.tickerID + ',' + settings.dom.revealID + ',' + settings.dom.titleID + ',' + settings.dom.titleElem + ',' + settings.dom.revealElem + ',' + settings.dom.contentID).stop(true, true);
$(settings.dom.revealID + ',' + settings.dom.revealElem).hide();
$(settings.dom.wrapperID)
.find(settings.dom.titleID + ',' + settings.dom.titleElem).show()
.end().find(settings.dom.contentID).show();
}
// play ticker
function restartTicker() {
settings.play = true;
settings.paused = false;
// start the ticker again
postReveal();
}
// change the content on user input
function manualChangeContent(direction) {
pauseTicker();
switch (direction) {
case 'prev':
if (settings.position == 0) {
settings.position = countSize(settings.newsArr) -2;
}
else if (settings.position == 1) {
settings.position = countSize(settings.newsArr) -1;
}
else {
settings.position = settings.position - 2;
}
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
break;
case 'next':
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
break;
}
// set the next content item to be used - loop round if we are at the end of the content
if (settings.position == (countSize(settings.newsArr) -1)) {
settings.position = 0;
}
else {
settings.position++;
}
}
});
};
// plugin defaults - added as a property on our plugin function
$.fn.ticker.defaults = {
speed: 0.10,
ajaxFeed: false,
feedUrl: '',
feedType: 'xml',
displayType: 'reveal',
htmlFeed: true,
debugMode: true,
controls: true,
titleText: '',
direction: 'ltr',
pauseOnItems: 3000,
fadeInSpeed: 600,
fadeOutSpeed: 300
};
})(jQuery);
/* Ticker Styling */
.ticker-wrapper.has-js {
margin: 0;
padding: 0;
width: 780px;
height: 32px;
display: block;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
background-color:inherit;
font-size: inherit;
}
.ticker {
width: 710px;
height: 23px;
display: block;
position: relative;
overflow: hidden;
background-color: #fff;
#media #{$xs}{
width: 200px;
}
}
.ticker-title {
padding-top: 9px;
color: #990000;
font-weight: bold;
background-color: #fff;
text-transform: capitalize;
}
.ticker-content {
margin: 0px;
/* padding-top: 9px; */
position: absolute;
color: #506172;
font-weight: normal;
background-color: #fff;
overflow: hidden;
white-space: nowrap;
font-family: "Roboto",sans-serif;
font-size: 16px;
}
.ticker-content:focus {
none;
}
.ticker-content a {
text-decoration: none;
color: #1F527B;
}
.ticker-content a:hover {
text-decoration: underline;
color: #0D3059;
}
.ticker-swipe {
padding-top: 9px;
position: absolute;
top: 0px;
background-color: #fff;
display: block;
width: 800px;
height: 23px;
}
.ticker-swipe span {
margin-left: 1px;
background-color: #fff;
border-bottom: 1px solid #1F527B;
height: 12px;
width: 7px;
display: block;
}
.ticker-controls {
padding: 8px 0px 0px 0px;
list-style-type: none;
float: left;
}
.ticker-controls li {
padding: 0px;
margin-left: 5px;
float: left;
cursor: pointer;
height: 16px;
width: 16px;
display: block;
}
.ticker-controls li.jnt-play-pause {
background-image: url('../images/controls.png');
background-position: 32px 16px;
}
.ticker-controls li.jnt-play-pause.over {
background-position: 32px 32px;
}
.ticker-controls li.jnt-play-pause.down {
background-position: 32px 0px;
}
.ticker-controls li.jnt-play-pause.paused {
background-image: url('../images/controls.png');
background-position: 48px 16px;
}
.ticker-controls li.jnt-play-pause.paused.over {
background-position: 48px 32px;
}
.ticker-controls li.jnt-play-pause.paused.down {
background-position: 48px 0px;
}
.ticker-controls li.jnt-prev {
background-image: url('../images/controls.png');
background-position: 0px 16px;
}
.ticker-controls li.jnt-prev.over {
background-position: 0px 32px;
}
.ticker-controls li.jnt-prev.down {
background-position: 0px 0px;
}
.ticker-controls li.jnt-next {
background-image: url('../images/controls.png');
background-position: 16px 16px;
}
.ticker-controls li.jnt-next.over {
background-position: 16px 32px;
}
.ticker-controls li.jnt-next.down {
background-position: 16px 0px;
}
.js-hidden {
display: none;
}
.no-js-news {
padding: 10px 0px 0px 45px;
color: #fff;
}
.left .ticker-swipe {
/*left: 80px;*/
}
.left .ticker-controls, .left .ticker-content, .left .ticker-title, .left .ticker {
float: left;
}
.left .ticker-controls {
padding-left: 6px;
}
.right .ticker-swipe {
/*right: 80px;*/
}
.right .ticker-controls, .right .ticker-content, .right .ticker-title, .right .ticker {
float: right;
}
.right .ticker-controls {
padding-right: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>Trending now</strong>
<!-- <p>Rem ipsum dolor sit amet, consectetur adipisicing elit.</p> -->
<div class="trending-animated">
<ul id="js-news" class="js-hidden">
<li class="news-item">Dolor sit amet, consectetur adipisicing elit.</li>
<li class="news-item">Spondon IT sit amet, consectetur.......</li>
<li class="news-item">Rem ipsum dolor sit amet, consectetur adipisicing elit.</li>
</ul>
</div>
The problem is that you are setting fixed widths for ticker elements.The ticker container has a width of 720px no matter what size the screen, and on screens < 767px the container for the scrolling text is just 230px.
Either change the CSS if it is your own, or if not you can add these rules after the Ticker CSS in included:
#media (max-width: 767px){
.ticker-wrapper.has-js,
.ticker,
.trending-tittle .ticker {
width: 100%!important;
}
}
This sets them to use the full width of the screen.
I'm trying to pull through a value from the dataLayer to fire a piece of HTML. All pulling through fine, however if the value is 'undefined' rather than an actual number I don't want it to fire.
How can I solve this? Tried everything but it's returning true/false rather than not firing.
$(document).ready(function () {
for (var i = 0, len = dataLayer.length; i < len; i++) {
if (dataLayer[i].event === "productView")
var viewed = dataLayer[i].P2;
}
function isOnScreen(element) {
var curPos = element.offset();
var curTop = curPos.top - $(window).scrollTop();
var screenHeight = $(window).height();
return (curTop > screenHeight) ? false : true;
}
var intervalId = setInterval(function () {
var addtocart = $('#add-to-cart');
if (isOnScreen(addtocart) === true) {
$('.product-image.main-image').before("<div id='social-overlay' style='color: #fff;text-transform: uppercase;font-family: Muli,Arial,Helvetica,sans-serif; font-size: 11px; font-weight: 800;background: #867dae; opacity: 0.8; padding-top: 10px; padding-bottom: 10px; position: absolute;z-index: 1; width: 100%;'>" + viewed + " people viewed item in the last 24 hours</div>")
setTimeout(function () {
$('#social-overlay').fadeOut(1000);
}, 7000);
clearInterval(intervalId);
}
}, 500);
});
Check if the variable 'viewed' is undefined in the setInterval function you have and add the html value using before function only if the viewed is valid.
var intervalId = setInterval(function() {
var addtocart = $('#add-to-cart');
if ( typeof viewed !== 'undefined' && isOnScreen(addtocart) === true) {
$('.product-image.main-image').before("<div id='social-overlay' style='color: #fff;text-transform: uppercase;font-family: Muli,Arial,Helvetica,sans-serif; font-size: 11px; font-weight: 800;background: #867dae; opacity: 0.8; padding-top: 10px; padding-bottom: 10px; position: absolute;z-index: 1; width: 100%;'>" + viewed + " people viewed item in the last 24 hours</div>") ;
setTimeout(function(){
$('#social-overlay').fadeOut(1000);
}, 7000);
clearInterval(intervalId);
}
}, 500);
I'm trying to implement my own confirmation box in JavaScript. But I don't want to change all the places where I have used window.confirm. So, I created proxy on window.confirm.
like,
(function (proxied) {
window.confirm = function () {
var res = MyConfirm.apply(this, arguments);
return res;
};
})(window.confirm);
The problem is, MyConfirm is based on promise but where ever confirm is there, its acting as boolean. What would be proper solution for this situation? Is it possible to make a custom function which works exactly like window.confirm?
Is there anyway, we can return boolean or other values from a function which depends on an async call?
You may be able to get the desired behavior with a custom confirmation dialog, I created a custom dialog control a while ago that gave me the ability to have a flexible modal confirmation dialog. I created a full sample jsFiddle here. For my needs, the dialog was part of a common js library and displays as soon as you instantiate it, and can include options for content, size, and confirmation button callbacks, but you could have a confirm function on the dialog object that does the work to initialize and display it, and return a response. Here's the complete code, which is also in the jsFiddle...
// Launch the dialog from a click on an element on the page
$("#launchDialog").click(function () {
showConfirmDialog();
})
function showConfirmDialog() {
//Define the dialog options
var dlgOptions = {
width: 300,
height: 150,
modal: true,
confirm: true,
confirmopts: {
closeOnOk: true,
question: "Are you sure?",
buttons: {
Ok: {
Label: "OK",
callback: dialogOkCallback
},
Cancel: {
Label: "Cancel",
callback: dialogCancelCallback
},
}
}
}
// Initialize the dialog object and display it
var dlg = MySite.Common.createDialog("confirmDialog", "Confirmation Required", "<p>Some additional dialog content here</p>", dlgOptions, document);
}
// Handle the OK response
function dialogOkCallback() {
$("#dialogresult").html("You clicked Ok");
}
// Handle the Cancel response
function dialogCancelCallback() {
$("#dialogresult").html("You clicked Cancel");
}
// Common library with dialog code
if (typeof (MySite) == "undefined")
{ MySite = { __namespace: true }; }
MySite.Common = {
createDialog: function (tagId, title, content, options, documentobj) {
var dlg;
var dlgLeft;
var dlgTop;
// Defaults
var dlgWidth = 210;
var dlgHeight = 140;
var dlgConfirmation = "";
var dlgConfirmationContainerHTML = "";
var dlgConfirmationContainer;
var isNewDialog;
var docBody;
var dlgTag;
var dlgModalBg;
var docObj;
// Take the document object passed in or default it, this is where the dialog div will be anchored
if (documentobj) {
docObj = documentobj;
}
else {
docObj = document;
}
docBody = $(docObj.body);
// Process the options if available
if (options) {
if (options.width) {
dlgWidth = options.width;
}
if (options.height) {
dlgHeight = options.height;
}
if (options.modal) {
// Set up the background div if this is a modal dialog
dlgModalBg = $(docObj.getElementById("dialogModalBackground"));
if (dlgModalBg.length == 0) {
docBody.append("<div id='dialogModalBackground' style='background-color: #000000; z-index:9998; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; opacity: 0.3;'> </div>");
} else {
dlgModalBg = docBody.find("#dialogModalBackground");
dlgModalBg.show();
}
}
}
// Do some dialog positioning
dlgLeft = (docObj.body.clientWidth / 2) - (dlgWidth / 2);
dlgTop = (docObj.body.clientHeight / 2) - (dlgHeight / 2) - 50;
// Make sure the dialog top value doesn't go negative
dlgTop = Math.max(dlgTop, 0);
dlg = $(docObj.getElementById(tagId));
// Create the dialog div
if (dlg.length == 0) {
isNewDialog = true;
docBody.append("<div id='dialogContainer_" + tagId + "' style='width: " + dlgWidth + "px; min-height: " + dlgHeight + "px; background-color: #ffffff; border: 1px solid darkgrey; z-index: 9999; position: absolute; top: " + dlgTop + "px; left: " + dlgLeft + "px;'><p id='dlgHeader' class='draggable_handle' style='color: #FFFFFF; margin: 0px; padding: 5px 1px 1px 5px; height: 18px; background-color: #005f9f; font-weight: bold; font-size: 1.2em; font-family: Arial;'>" + title + "<span style='float: right; font-size: 0.8em; cursor: pointer; padding-right: 4px;' id='dialogClose_" + tagId + "'>Close</span></p><div style='padding: 0px; margin: 0px 2px 0px 2px; min-height: " + (dlgHeight - 24).toString() + "px;' id='" + tagId + "'></div></div>");
dlg = docBody.find("#" + tagId);
} else {
isNewDialog = false;
dlg.html("");
docBody.find("#dialogContainer_" + tagId).show();
}
// Make the dialog draggable if that feature is available
if ($.ui) {
if ($.ui.draggable) {
docBody.find("#dlgHeader").css("cursor", "move");
docBody.find("#dialogContainer_" + tagId).draggable({ handle: ".draggable_handle" });
}
}
if (content) {
dlg.html(content);
}
// Create or update the confirmation dialog content
dlgConfirmationContainer = docBody.find("#Confirmation_" + tagId);
// Set up the buttons if this is a confirmation dialog
if (options.confirm == true) {
if (options.confirmopts.question != null) {
dlgConfirmation += options.confirmopts.question + "<br/><br/>";
}
if (options.confirmopts.buttons.Ok.Label != null) {
dlgConfirmation += "<input id='dialogOk_" + tagId + "' style='width: 45%' type='button' value='" + options.confirmopts.buttons.Ok.Label + "'/> ";
}
if (options.confirmopts.buttons.Cancel != null && options.confirmopts.buttons.Cancel.Label != null) {
dlgConfirmation += "<input id='dialogCancel_" + tagId + "' style='width: 45%' type='button' value='" + options.confirmopts.buttons.Cancel.Label + "'/>";
}
if (dlgConfirmationContainer.length == 0) {
dlg.append("<div id='Confirmation_" + tagId + "' style='padding: 3px'>" + dlgConfirmation + "</div>");
} else {
dlgConfirmationContainer.show();
dlgConfirmationContainer.html(dlgConfirmation);
}
} else {
dlgConfirmationContainer.hide();
}
// Assign click events if this is a confirmation dialog. the jQuery click() assignment normally would APPEND click events to
// the object, but those are lost when the div container html is reassigned above, so we assign the click each time this function
// is called.
if (options.confirm) {
docBody.find("#dialogOk_" + tagId).click(function (event) {
event.preventDefault();
if (options.confirmopts.closeOnOk == true) {
docBody.find("#dialogContainer_" + tagId).hide();
docBody.find("#dialogModalBackground").hide();
}
if (!options.confirmopts.keepOnOk) {
docBody.find("#Confirmation_" + tagId).hide();
}
if (options.confirmopts.buttons.Ok.callback != null) {
options.confirmopts.buttons.Ok.callback();
}
});
docBody.find("#dialogCancel_" + tagId).click(function (event) {
event.preventDefault();
docBody.find("#dialogContainer_" + tagId).hide();
docBody.find("#dialogModalBackground").hide();
if (options.confirmopts.buttons.Cancel.callback != null) {
options.confirmopts.buttons.Cancel.callback();
}
});
}
docBody.find("#dialogClose_" + tagId).click(function (event) {
event.preventDefault();
docBody.find("#dialogContainer_" + tagId).hide();
docBody.find("#dialogModalBackground").hide();
});
dlg.closeDialog = function () {
docBody.find("#dialogContainer_" + tagId).hide();
docBody.find("#dialogModalBackground").hide();
};
return dlg;
},
__namespace: true
};