How can i get the if else statement working - javascript

I want to implement a if else javascript code in my gtm that will send a popup to tell my visitors on my website that if adblock is enabled they have to disable to proceed. The code below doesn't seem to be working because its always the same statement that is displayed.
var adBlockDetected = false;
if (adblockerDetected()) {  
adBlockDetected = true;  
alert("Varning! Du har en adblocker aktiverad. Vänligen inaktivera den för att se alla annonser på vår webbplats.");
}
function adblockerDetected() {}
if (!adBlockDetected) {  
alert("Adblocker är inaktiverat. Du kommer att se alla annonser på vår webbplats.");
}

Code implementation must be inside of adblockerDetected() function:
function adblockerDetected() {
if (!adBlockDetected) {
alert("Adblocker är inaktiverat. Du kommer att se alla annonser
på vår webbplats.");
}
}

Related

Problema com a barra de progresso e o DOM [closed]

Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 6 days ago.
Improve this question
fiz uma barra de progresso em um projeto, seguindo essa lógica:
`const carregarBarra = () => {
const totalPercent = 100;
const totalProperties = Object.keys(data).length;
let porcentagem = (totalPercent * validatedInputs) / totalProperties;
if(data.produto){
validatedInputs += 1
}
if(data.quantidade){
validatedInputs += 1
}
if(data.preco){
validatedInputs += 1
}
if(data.tipoDoProduto){
validatedInputs += 1
}
console.log("porcentagem:",porcentagem)
console.log("inputs preenchidos: ",validatedInputs)
return porcentagem
}`
Então, eu coloco o valor de carregarBarra() em um width para mostrar o progresso conforme o usuário preenche os inputs, assim que todos os 4 são preenchidos o input de submit deveria ser ativado imagem do Modal.
O problema é o seguinte: o valor de "porcentagem" deve ser 100 de acordo com essa lógica, para assim desativar o disabled do input "submit", porém na DOM a barra carrega os 100% mas no console o valor de "porcentagem" é 200, mesmo não havendo nada multiplicando ela fora dessa função.
<input type="submit" value='Salvar' disabled={carregarBarra() !== 100} />
console após o preenchimento de todos os inputs
compreender oq esta havendo que o valor de porcentagem esta duplicando no console

Changing a HTML <p> to a string-value from an object

I am sure this has been asked before but I am such a beginner at this that I dont think I would recognize the answer even if I happened stumbled upon it.
I am wondering why my code is not doing what it is meant to. It is supposed to take a value from the object event1 and copy it into the HTML p-tags and button-tags. Am I trying to do something completely ignorant?
var event1 = {
situation: "Du befinner dig hemma i soffan. Det är mörkt utomhus och TVn är påslagen. På soffbordet ser du ett tomt glas och en flaska vodka.",
val1: "1. Stäng av TVn",
val2: "2. Gå utomhus",
val3: "3. Fyll glaset med vodka";
};
document.getElementById("event").innerHTML = event1.situation();
document.getElementById("choice1").innerHTML = event1.val1();
document.getElementById("choice2").innerHTML = event1.val2();
document.getElementById("choice3").innerHTML = event1.val3();
<p id="event"></p>
<p>Vad vill du göra?</p>
<button type="button" id="choice1"></button>
<button type="button" id="choice2"></button>
<button type="button" id="choice3"></button>
My Code in JSFiddle
Also an extra question: Can I nest objects inside objects or is that not possible?
There was a syntax error in the object after val3 (the semicolon), and you would need the parenthesis if you were calling a function, but you are just referencing a value, so it is not appropriate.
I believe this is what you're looking for:
var event1 = {
situation: "Du befinner dig hemma i soffan. Det är mörkt utomhus och TVn är påslagen. På soffbordet ser du ett tomt glas och en flaska vodka.",
val1: "1. Stäng av TVn",
val2: "2. Gå utomhus",
val3: "3. Fyll glaset med vodka"
};
document.getElementById("event").innerHTML = event1.situation;
document.getElementById("choice1").innerHTML = event1.val1;
document.getElementById("choice2").textContent = event1.val2;
document.getElementById("choice3").innerHTML = event1.val3;
first never close a object second event1.wherever is not a function try this way :)
var event1 = {
situation: "Du befinner dig hemma i soffan. Det är mörkt utomhus och TVn är påslagen. På soffbordet ser du ett tomt glas och en flaska vodka.",
val1: "1. Stäng av TVn",
val2: "2. Gå utomhus",
val3: "3. Fyll glaset med vodka"
};
document.getElementById("event").innerHTML = event1.situation;
document.getElementById("choice1").innerHTML = event1.val1;
document.getElementById("choice2").innerHTML = event1.val2;
document.getElementById("choice3").innerHTML = event1.val3;
console.log(event1.situation)
<p id="event"></p>
<p>Vad vill du göra?</p>
<button type="button" id="choice1"></button>
<button type="button" id="choice2"></button>
<button type="button" id="choice3"></button>
Check this pen.
Updated code:
var event1 = {
situation: "Du befinner dig hemma i soffan. Det är mörkt utomhus och TVn är påslagen. På soffbordet ser du ett tomt glas och en flaska vodka.",
val1: "1. Stäng av TVn",
val2: "2. Gå utomhus",
val3: "3. Fyll glaset med vodka"
}
document.getElementById("event").innerHTML = event1.situation
document.getElementById("choice1").innerHTML = event1.val1
document.getElementById("choice2").innerHTML = event1.val2
document.getElementById("choice3").innerHTML = event1.val3
Errors in original code: semi-colon at end of line 5. Semi-colons are illegal in objects. Commas and colons only.
References to object were using a 'method' style of syntax, whereas the contents of the object are properties.

Jquery Animate delay even though no delay Why?

I am encountering a problem with jquery. The problem is, I have made an animation on an ".info" div box. I want it to slide into the document and then slide out again when you deselect a button - the sliding in works fine, but when you deselect there is a delay of 20 seconds or so. I have no idea where this delay comes from. Can you help me?
The link is: http://ljensenphoto.dk/dokken/dokken.html
Javascript code (sorry for the comments - I have written these to help myself, I am obviously new to Javascript and jquery :D ):
$(document).on("ready");
//to variabler - kan ændre værdien.
var selected;
var info;
//to konstante. Her definerer vi værdien af de to cirklers farver :D. Den første definerer hvilken farve cirklen skal have når der IKKE er klikket på den. Den anden definerer hvilken farve cirklen skal have, når vi har klikket på den.
const colorNeutral = "";
const colorSelected = "#d8ff00";
//loader SVG ind i dokumentet. Det første er "selectoren", der vælger noget i DOM - HTML'en. "" = Strings.
$("#dokkenkort").load("Dokken.svg", loadSvg);
//loader JSON ind i dokumentet
function loadSvg(){
$.getJSON("dokken.JSON", loadJSON);
}
function loadJSON(data) {
info = data;
$("#info g").on("click", circleClick);
}
function circleClick(event) {
console.log("Det virker sguda!!!!");
if (event.delegateTarget == selected) {
console.log("Klikkede på det samme som allerede er valgt!");
// Gør så sidste klik bliver glemt og nulstilles.
$(selected).children().attr("fill", colorNeutral);
//Følgende giver en ekstra attribut til en selector.
//$(selected).children().attr("r", 6);
// Glemmer hvad der blev selected
selected = null;
$(".info").animate({top:"1000px"},500,clear);
// Clearer info-div-boksen
function clear(){$(".info").text("");}
} else {
console.log("klik på et nyt element!");
// Disabler forrige selection.
$(selected).children().attr("fill", colorNeutral);
//Følgende giver en ekstra attribut til en selector.
//$(selected).children().attr("r", 6);
// husker hvad der blev selected (bliver gemt i "selected" som vi defineret som en variabel øverst)!
selected = event.delegateTarget;
console.log(selected.id)
// mark selected
$(selected).children().attr("fill", colorSelected);
// display info on selected
showInfo();
}
}
//udskriver teksten!
function showInfo( ) {
// find info in info-array
$.each(info, findSelectedInfo);
console.log("Hey man! FindSelectedInfo");
}
function findSelectedInfo(key, value) {
if (value.sted == selected.id) {
console.log("Indeni if");
$(".info").html("<h1>"+value.overskrift+"</h1>");
$(".info").append("<p>"+value.tekst+"</p>");
$(".info").append("<img src='"+value.billed+"' alt='"+value.sted+"'>");
}
$(".info").animate({top:"500px"},3000);
}
Thanks in advance!
Best regards
Kalle Jensen.

jQuery / Js — Accessing Variables in a Function

I'm trying to streamline my code a little by setting up functions rather than repeating the same lines of code over again:
function pledgeSpanish() {
$(name).attr('placeholder', 'Tu nombre... *');
$(email).attr('placeholder', 'Tu correo electrónico... *');
$(nationality).text('Nacionalidad....');
$(radioPublic).text('Soy miembro del compromiso global de apoyo a las comunidades afectadas por las mineras.');
$(radioCommunity).text('Provengo o trabajo en una comunidad afectada por las mineras. Me gustaría contactar con otros miembros del movimiento “Si a la Vida, No a la Minera” y recibir las últimas actualizaciones.');
$(buttonSubmit).val('Firma La Petición');
}
But when I try to run the script, I get the error
email is not defined
Funnily enough, I don't get an error for the 'name' field
How would I go about modifying it so that I can access the variables from within the function?
Amended like so:
var name = $('#form-pledge .field-name input');
var email = $('#form-pledge .field-email input');
var nationality = $('#form-pledge .field-nationality select option:first');
var radioPublic = $('#form-pledge .gfield_radio li:first label');
var radioCommunity = $('#form-pledge .gfield_radio li:last label');
var buttonSubmit = $('#form-pledge input[type="submit"]');
function pledgeSpanish() {
$(name).attr('placeholder', 'Tu nombre... *');
$(email).attr('placeholder', 'Tu correo electrónico... *');
$(nationality).text('Nacionalidad....');
$(radioPublic).text('Soy miembro del compromiso global de apoyo a las comunidades afectadas por las mineras.');
$(radioCommunity).text('Provengo o trabajo en una comunidad afectada por las mineras. Me gustaría contactar con otros miembros del movimiento “Si a la Vida, No a la Minera” y recibir las últimas actualizaciones.');
$(buttonSubmit).val('Firma La Petición');
}
Is this the best way to go about it?

Youtube API - equivalent of onTime

I am looking for a similar event in OnTime (jwplayer) in YouTube API.
More precisely, with jwplayer, I used the following function that I would fit with the youtube player:
//Fonction destinée à afficher des notes en fonction de la progression des vidéos lues
jwplayer("mediaplayer").onTime(function(event)
{
switch (jwplayer().getPlaylistItem().title)
{
case 'Séquence 1':
if (event.position >=42 && event.position <=70 )
{
setText("CANGUILHEM, Georges, <i>Le normal et le pathologique</i>, Paris, PUF, 1972.");
}
else if (event.position >=1257 && event.position <=1268 )
{
setText("CANGUILHEM, Georges, <i>Essai sur quelques problèmes concernant le normal et le pathologique</i>, thèse de doctorat en médecine, 1943.");
}
else {setText("Retrouvez ici des notes destinées à préciser un point particulier de l'intervention.")};
break;
case 'Séquence 2':
{setText("Retrouvez ici des notes destinées à préciser un point particulier de l'intervention.")};
break;
default:
setText("Retrouvez ici des notes destinées à préciser un point particulier de l'intervention.");
break;
}
});
function setText(text)
{
document.getElementById("message").innerHTML = text;
}
Does anyone have an idea how I could adapt it?
use javascript setInterval to execute a function at specified interval.
function onTime(){
console.log("executing at specified interval")
};
window.setInterval(onTime, 3000);
http://www.w3schools.com/jsref/met_win_setinterval.asp
within this function, to mimic the jwplayer onTime function, you'll probably have to perform a check to see if the video is playing before executing your custom code. perhaps something like:
function onTime(){
var player_state = player.getPlayerState();
if(player_state == 1){
var player_position = player.getCurrentTime()
console.log("the video is playing!", player_position)
}
};
Why don't you use this : player.getDuration(); You can find documentation here :
https://developers.google.com/youtube/js_api_reference#Retrieving_video_information
something like :
var time = player.getDuration();
if (time == "le temps que tu veux") {
// ton code ici...
}
Hope it will help...

Categories