Alert box to accept cookies in a web site - javascript

I wanna know how to put a .js code in a button that it's in a bootstrap alert that when the user clicked accept, the alert box no appear again.
Thanks a lot.
This is the code that I have, but doesn't work.
JS:
$(".btn_cerrar").on({
click: function(){
location.reload(
$(".pb-element-alert").hidden();
});
});
<div id="modal">
<p style="text-align: center;">Este sitio web emplea cookies para ofrecerle un servicio más</p>
<p> personalizado.</p>
<p style="text-align: center;">Si continúa navegando entenderemos que acepta nuestra</p>
<p style="text-align: center;"><a title="Politicas" href="images/eventos/POLITICA_DE_TRATAMIENTOS_DE_DATOS.pdf" target="_blank"><strong>Políticas de tratamiento de la información</strong></a> de nuestro sitio web.</p>
<button class=" btn_cerrar btn pull-right btn-success" type="button" data-dismiss="alert"> Aceptar</button></div>
HTML:
`
Este sitio web emplea cookies para ofrecerle un servicio más
 personalizado.
Si continúa navegando entenderemos que acepta nuestra
Políticas de tratamiento de la información de nuestro sitio web.
Aceptar
`

I am not sure what exactly is the alert you are talking about since it is not shown in your html.
The correct syntax of your script should be that:
$(".btn_cerrar").on('click', function(){
// Do what you want.
});
Now if the element you want hide can be selected from the selector $(".pb-element-alert") you mention in your question then you can use this:
$(".pb-element-alert").hide();
All of it together would be:
$(".btn_cerrar").on('click', function(){
$(".pb-element-alert").hide();
});
UPDATE
$( document ).ready(function() {
bool isBtnClicked = sessionStorage.getItem('buttonClicked') == true;
if(isBtnClicked){
$(".pb-element-alert").hide();
}
});
$(".btn_cerrar").on('click', function(){
sessionStorage.setItem('buttonClicked', true);
$(".pb-element-alert").hide();
});

Related

Copying all HTML contents from one div to another using jQuery

This question may seem as a duplicate one, but I cannot seem to find a solution for my problem.
I am fetching content from external websites using the iFramely API. Which works for almost all requested websites.
However, if I try to fetch for example a post from Reddit and display this in a sort of custom made 'preview box' the requested iFrame get rendered correctly, so far so good.
When I try to copy the HTML content of the 'preview box' in order to append it to another div using jQuery. It does not copy all HTML elements.
Complete function
$('#btn-add-extern-snippet').click(function() {
let embed_preview_container = $('#embed-preview');
let embed_target_number = $('#embed-target-number');
let target_number = $(embed_target_number).val();
$('.embed-no-' + target_number).html($(embed_preview_container).html());
...
});
I've tried the jQuery functions:
clone $('.embed-no-' + target_number).html($(embed_preview_container).clone());
html $('.embed-no-' + target_number).html($(embed_preview_container).html());
contents $('.embed-no-' + target_number).html($(embed_preview_container).contents());
using append $('.embed-no-' + target_number).append($(embed_preview_container).html());
But all of these functions do not seem the copy the full "innerHTML" of the mentioned 'preview box' (see pictures below).
The copied HTML content inside the 'other div' with an empty body & head.
The actual content in side the 'preview box'.
I must note here that this only seems to be te case for Reddit related content. It works for example with Soundcloud/Spotify/Bandcamp.
PS. I am using jQuery version 3.3.1
Code sample below:-
$("#copyToDiv").append($("#copyFromDiv").html());
Thanks
you can try this.
$('#copy').click(function(){
$('#div2').html($('#div1').html());
});
#div1{
background:green;
}
#div2{
background:blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='copy'>Copy</button>
<div id='div1'>
<p>Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. Le Lorem Ipsum est le faux texte standard de l'imprimerie depuis les années 1500, quand un imprimeur anonyme assembla ensemble des morceaux de texte pour réaliser un livre spécimen de polices de texte. Il n'a pas fait que survivre cinq siècles, mais s'est aussi adapté à la bureautique informatique, sans que son contenu n'en soit modifié. Il a été popularisé dans les années 1960 grâce à la vente de feuilles Letraset contenant des passages du Lorem Ipsum, et, plus récemment, par son inclusion dans des applications de mise en page de texte, comme Aldus PageMaker.
</p>
<div>
<h2>Lorem Ipsum</h2>
<p>Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. Le Lorem Ipsum est le faux texte standard de l'imprimerie depuis les années 1500, quand un imprimeur anonyme assembla ensemble des morceaux de texte pour réaliser un livre spécimen de polices de texte. Il n'a pas fait que survivre cinq siècles, mais s'est aussi adapté à la bureautique informatique, sans que son contenu n'en soit modifié. Il a été popularisé dans les années 1960 grâce à la vente de feuilles
</p>
</div>
<div id='div2'></div>
Alright, so I've found the solution/workaround to my own problem. Instead of copying the contents of the 'preview box', I stored the fetched HTML in a temporary variable, and appended the contents of this variable inside an 'another div' (this works).
Noteworthy, something strange that occurred to me while debugging is that the browser (in this case Chrome), does not render/display HTML correctly (see picture) (note the empty iFrame).
This is exactly what .html() copied. So long story short the following code worked for me:
// temporary variable for storing html.
let currentSnippet = '';
$('#btn-add-extern-snippet').click(function() {
let embed_preview_container = $('#embed-preview');
let embed_target_number = $('#embed-target-number');
let target_number = $(embed_target_number).val();
$('.embed-no-' + target_number).html(currentSnippet);
...
});

Show multiple divs on button click

Firstly i would say sorry because my english isn't so good but i will try my best.
So i will explain you my problem, i would like to show all my divs when the users click on a button. It's really complicate for me becase there is a lot of id. It's like a drop menu.
My code :
$("#content_caract_1").hide();
$("#content_caract_2").hide();
$("#content_caract_3").hide();
$("#content_caract_4").hide();
$('#btnd').click(function() { // Au clic sur un élément
$(".forbutton").toggle(400); // chache ou affiche a une vitesse constante (400)
});
$('#caract1').click(function() { // Au clic sur un élément
$("#content_caract_1").toggle(400); // chache ou affiche a une vitesse constante (400)
});
$('#caract1bis').click(function() { // Au clic sur un élément
$("#content_caract_1bis").toggle(400); // chache ou affiche a une vitesse constante (400)
});
$('#caract1bis2').click(function() { // Au clic sur un élément
$("#content_caract_1bis2").toggle(400); // chache ou affiche a une vitesse constante (400)
});
$('#caract1bis3').click(function() { // Au clic sur un élément
$("#content_caract_1bis3").toggle(400); // chache ou affiche a une vitesse constante (400)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btnp" value="Tout plié">
<input type="button" id="btnd" value="Tout déplié">
<div id="caract1">
<h2>Etape 1 : Les enjeux et le parcours</h2>
</div>
<div class="forbutton">
<div id="content_caract_1">
<p>Equitis Romani autem esse filium criminis loco poni ab accusatoribus neque his iudicantibus oportuit neque defendentibus nobis. Nam quod de pietate dixistis, est quidem ista nostra existimatio, sed iudicium certe parentis; quid nos opinemur, audietis
ex iuratis; quid parentes sentiant, lacrimae matris incredibilisque maeror, squalor patris et haec praesens maestitia, quam cernitis, luctusque declarat.</p>
<div id="caract1bis">
1.1 Enjeux du programme Appolo</br>
</div>
<div id="content_caract_1bis">
<p>test</p>
</div>
<div id="caract1bis2">
1.2 Retour d'experience</br>
</div>
<div id="content_caract_1bis2">
<p>test</p>
</div>
<div id="caract1bis3">
1.3 Votre parcours
</div>
<div id="content_caract_1bis3">
<p>test</p>
</div>
</div>
</div>
There is 4 block like this, i would like to click on the button et show all the things inside the block.
Thanks to you had read me ! If you need more precision, im here to answer.
Thanks
Nico
You could assign a class to everything you need to be "toggable"
<div class="toggable">
one
</div>
<div class="toggable">
two
</div>
<button id="hide-stuff">
toggle
</button>
Then catch the all in one call like this
$('#hide-stuff').click(function() {
$('.toggable').toggle();
})
You are toggling your parent div on button click and hiding all its children on page load. Just toggle parent div on page load.
<script>
$(".forbutton").hide();
//$("#content_caract_1").hide();
//$("#content_caract_2").hide();
//$("#content_caract_3").hide();
//$("#content_caract_4").hide();
$('#btnd').click( function() { // Au clic sur un élément
$(".forbutton").toggle(400);// chache ou affiche a une vitesse constante (400)
});
$('#caract1').click( function() { // Au clic sur un élément
$("#content_caract_1").toggle(400);// chache ou affiche a une vitesse constante (400)
});
$('#caract1bis').click( function() { // Au clic sur un élément
$("#content_caract_1bis").toggle(400);// chache ou affiche a une vitesse constante (400)
});
$('#caract1bis2').click( function() { // Au clic sur un élément
$("#content_caract_1bis2").toggle(400);// chache ou affiche a une vitesse constante (400)
});
$('#caract1bis3').click( function() { // Au clic sur un élément
$("#content_caract_1bis3").toggle(400);// chache ou affiche a une vitesse constante (400)
});
$("#content_caract_1").find("div").hide();
$('#btnp').click( function() { // Au clic sur un élément
$("#content_caract_1").find("div").show();// chache ou affiche a une vitesse constante (400)
});
$('#btnd').click( function() { // Au clic sur un élément
$("#content_caract_1").find("div").hide();// chache ou affiche a une vitesse constante (400)
});

Jquery Ajax request executing multiple times

everyone. I have the following code which intercepts forms submition and make a Ajax call:
$(function () {
$('form').each(function (id, el) {
$(el).submit(function (event) {
event.preventDefault();
var _data = $(this).serialize();
alert(id);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: _data
})
.done(function (response) {
if (response === '') {
notifySuccess("Já recebemos sua história! Obrigado por compartilhá-la conosco!");
$(el).find('textarea').val(' ');
} else {
notifyAlert(response);
}
})
.fail(function(data) {
notifyAlert(data.responseText);
});
grecaptcha.reset($(this).find('button').attr('id'));
});
});
$('textarea').click(function () {
if($(this).val() === ' ')
$(this).val('');
});
});
The code seems to be ok. However, when I run the site in my browser and put a breakpoint at line $.ajax({, it shows to me that it's executed 4 times when I try to submit a form. For debug reasons, I put a alert(id) to see what form it was submitting. My surprise is that the alert executes with the correct form ID, and a single time. In other words, only the AJAX line gets executed 4 times. The code before it don't. It's worthy to note that the callbacks (.done and .fail) also execute only one time. What can be happening here?
Here is the entire code:
var onLoadRecaptcha = function () {
$('form').each(function (id, el) {
$(el).ready(function () {
var submit = function () {
$(el).submit();
}
var _id = grecaptcha.render(
$(el).find('button').get(0),
{
'sitekey': '6LeDwBoUAAAAANMD7VBNK2F2agKXl6rduUlelf5U',
'callback': submit
}
);
$(el).find('button').attr('id', _id);
});
});
}
$(function () {
$('form').each(function (id, el) {
$(el).submit(function (event) {
event.preventDefault();
var _data = $(this).serialize();
alert(id);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: _data
})
.done(function (response) {
if (response === '') {
notifySuccess("Já recebemos sua história! Obrigado por compartilhá-la conosco!");
$(el).find('textarea').val(' ');
} else {
notifyAlert(response);
}
})
.fail(function(data) {
notifyAlert(data.responseText);
});
grecaptcha.reset($(this).find('button').attr('id'));
});
});
$('textarea').click(function () {
if($(this).val() === ' ')
$(this).val('');
});
});
var notifyAlert = function (message) {
$("#notify-modal").find('.modal-body').removeClass('alert-success');
$("#notify-modal").find('.modal-body').addClass('alert-danger');
$("#notify-modal").find('.modal-body').text(message);
$("#notify-modal").modal('show');
}
var notifySuccess = function (message) {
$("#notify-modal").find('.modal-body').removeClass('alert-danger');
$("#notify-modal").find('.modal-body').addClass('alert-success');
$("#notify-modal").find('.modal-body').text(message);
$("#notify-modal").modal('show');
}
<!doctype html>
<?php
// error_reporting(0);
require_once('scripts/connect.php');
//require_once('scripts/fb.php');
$res = mysqli_query($mysqli, "SELECT * FROM `personas`");
?>
<html class="no-js" lang="pt-BR">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Campanha Anti-bullying | UNASP-EC</title>
<meta name="description" content="Uma campanha anti-bullying bem bacaninha">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Oswald:300,400" rel="stylesheet">
<link href="style.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script>
<script>window.html5 || document.write('<script src="js/vendor/html5shiv.js"><\/script>')</script>
<![endif]-->
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<section>
<div class="fill-viewport cover d-flex flex-column justify-content-center align-items-center text-uppercase container" style="background-color: #000; color: #FFF">
<img class="img-fluid" src="images/cover_text.png" alt="Bullying, esta brincadeira não tem graça!" />
</div>
</section>
<section> <!-- Apresentação -->
<div class="container my-5 text-justify stylize-text">
<p>O sol queimava, mas dentro da menina magra e de cabelos crespos existia uma tempestade provinda do Alasca. O céu se estendia num azul pintado de anil, porém, a menina tímida de pequeno porte, o enxergava cinza. Os pássaros cantavam, no entanto, a menina de óculos e pele negra ouvia apenas um tom dissonante. Talvez hoje o som seja algo semelhante ao da trilha de Bernard Herrmann no filme Psicose.</p>
<p>— Mãe, me dá R$0,50? — perguntou a pequena de oito anos.</p>
<p>— Por que você quer esse dinheiro? — retrucou a mãe desconfiada.</p>
<p>— Por nada mãe, eu só quero — respondeu, agora com os olhos lacrimejados.</p>
<p>A mãe não tinha ideia do que acontecia e atordoada com os fatos relatados pela filha, se viu sem forças para continuar o caminho tortuoso até a escola.</p>
<p>— Mãe ela me bate quando não dou o dinheiro e todos os dias eles me xingam e me deixam sozinha no recreio.</p>
<p>O trecho acima poderia ser facilmente confundido com aquelas histórias ficcional, não fosse um fato vivido por 46,6% dos alunos entrevistados pelo Instituto Brasileiro de Geografia e Estatística (IBGE). O último senso confirmou o crescimento significativo desde o último levantamento feito em 2012, onde apontou 35,3% o número de vítimas nas escolas. De acordo com a pesquisa, 7,4% dos entrevistados atribuíram a aparência como principal motivo para as agressões.</p>
<p>De acordo com o Código Civil Brasileiro, o <i>bullying</i> é crime e resulta em pena ao agressor, podendo ser advertência ou até mesmo restrição de liberdade. Alessandra Borelli, advogada e coordenadora do <i>Manual de Boas Práticas para Uso Seguro das Redes Sociais</i> da Ordem dos Advogados do Brasil de São Paulo (OAB/SP) e coordenadora do guia <i>Conhecendo para Prevenir bullying< e Cyberbullying</i>, explica as consequências de causar dano moral ou físico ao outro e lembra ser obrigação do agressor, dos pais ou até mesmo da escola reparar a ofensa. “Logo, se um menor for responsável pela prática de <i>bullying</i>, muito embora a legislação privilegie a adoção de medidas voltadas à orientação e resgate da boa disciplina, nada impede que a vítima do <i>bullying</i> promova medidas legais buscando a reparação dos danos suportados”, destaca. Ainda de acordo com Alessandra é responsabilidade de todos, família e escola, prestar ajuda necessária a vítimas de <i>bullying</i>, com o intuito de aliviar as consequências da agressão. “Considerando os aspectos morais que alicerçam as relações entre pais e filhos, alunos, escola e sociedade em geral, todos somos responsáveis e se, ao notarmos sinais de vítimas ou agressores em nossos filhos e alunos, devemos agir tempestivamente. Famílias e escolas precisam caminhar juntas”, pontua.</p>
<p>O Centro Universitário Adventista de São Paulo (Unasp), campus Engenheiro Coelho, entende o <i>bullying</i> como um problema real na vida de crianças e jovens e por esse motivo, aderiu à campanha “Essa brincadeira não tem graça”, com o objetivo de conscientizar vítimas e agressores, alunos de escolas e universidades públicas e privadas para a luta contra o <i>bullying</i>.</p>
</div>
</section>
<section> <!-- Imprensa -->
<div class="container py-5">
<h1>Imprensa</h1>
</div>
</section>
<section> <!-- Eu Cuido de Você -->
<div class="container py-5">
<h1>Eu Cuido de Você</h1>
<p class="text-justify stylize-text">Você acompanhou histórias reais de brincadeiras sem graça, mas isso não precisa continuar. Nós entendemos o momento difícil e delicado que envolve uma agressão, mas você deve saber que não está sozinho. O Unasp preparou uma equipe de psicólogos para te ajudar. Tudo o que você precisa fazer é nos contar sua história. Fique a vontade e desabafe nos comentários abaixo sobre o que você enfrenta em seu dia-a-dia. Fique tranquilo, pois não vamos contar para ninguém. Queremos cuidar de você!</p>
<ul class="list-unstyled form-list">
<?php while ($persona = $res->fetch_array(MYSQLI_ASSOC)) { ?>
<li class="card card-inverse rounded-0 mb-4" style="background-color: #333;">
<div class="card-block">
<form id="story-<?php echo $persona['id']; ?>" action="scripts/story_submit.php" method="post" class="h-100">
<input name="id" type="hidden" value="<?php echo $persona['id']; ?>" />
<div class="d-flex form-body">
<div class="d-flex flex-column">
<img src="./images/personas/<?php echo htmlspecialchars($persona['image']); ?>" alt="" />
<span class="persona-caption"><?php echo htmlspecialchars($persona['name']); ?></span>
</div>
<div class="d-flex flex-column w-100">
<textarea name="story" class="form-control" maxlength="500" required></textarea>
<button class="btn btn-primary g-recaptcha">Enviar</button>
</div>
<div class="recaptcha"></div>
</div>
</form>
</div>
</li>
<?php } ?>
</ul>
</div>
</section>
<!-- Notify Modal -->
<div class="modal fade" id="notify-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog " role="document">
<div class="modal-content">
<div class="modal-body alert mb-0">
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script src="script.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onLoadRecaptcha&render=explicit" async defer></script>
</body>
</html>
<?php
$res->free();
$mysqli->close();
?>
Your issue is
$('form').each(function (id, el) {
$(el).submit(function (event) {
id is the index and el is the element (form). see here: https://api.jquery.com/each/
Just add the event handler
$('form').submit(function (event) {
That says "Find all the form elements present, add an event handler for submit."
Now inside that alert(id); change to alert($(this).index());
Thus your index (as shown) is the "id" of the element as you had it.
return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.Event object.
This should address that.
$(function() {
$('form').on('submit', function(event) {
event.preventDefault();
event.stopPropagation();// could have "return false;" at the end
var me = $(this);
var myid = $(this).index();
alert(myid); // not that this IS needed...
var _data = me.serialize();
$.ajax({
type: 'POST',
url: me.attr('action'),
data: _data
})
.done(function(response) {
if (response === '') {
notifySuccess("Já recebemos sua história! Obrigado por compartilhá-la conosco!");
me.find('textarea').val(' ');
} else {
notifyAlert(response);
}
})
.fail(function(data) {
notifyAlert(data.responseText);
});
// just to be clear, this happens NOW, before the ajax completes
// is that what is desired?
grecaptcha.reset(me.find('button').attr('id'));
// return false; // instead of event.xx above
});
$('textarea').click(function() {
if ($(this).val() === ' ')
$(this).val('');
});
});
Side note
$("#notify-modal").find('.modal-body').removeClass('alert-success');
$("#notify-modal").find('.modal-body').addClass('alert-danger');
$("#notify-modal").find('.modal-body').text(message);
can perhaps be (avoid multiple DOM traversals)
$("#notify-modal").find('.modal-body')
.removeClass('alert-success')
.addClass('alert-danger')
.text(message);

Why does returning from other web leave the last hash while showing the content of the first one?

Problem: After I input a name and hit enter, the hash changes to 'pag2', showing different content. I click the red link that goes to other website and, once I am on that website, I go back via back button in the browser. It still is www.luisalmerich.com#pag2, but shows the content from the empty location hash (the one you see entering directly).
If I have explained it badly:
www.luisalmerich.com -> I input the text and hit enter -> www.luisalmerich.com/#pag2 -> www.siroppe.com (red link on #pag2) -> Back button on browser -> www.luisalmerich.com/#pag2 but with the content from www.luisalmerich.com
This is the web: http://www.luisalmerich.com/
My code isn't anything weird. Here is all the JavaScript the website has (it's probably causing the problem):
$(document).ready(function () {
$('#input1').keypress(function (e) {
if(e.which == 13){
location.hash="pag2";
}
});
});
$(window).on('hashchange', function() {
if (location.hash == "#pag2") {
$('#pag1').css("display", "none");
$('#pag2').css("display", "block");
$('#pag3').css("display", "none");
} else if (location.hash == "#pag3") {
$('#pag1').css("display", "none");
$('#pag2').css("display", "none");
$('#pag3').css("display", "block");
} else {
$('#pag1').css("display", "block");
$('#pag2').css("display", "none");
$('#pag3').css("display", "none");
}
});
And here is the important html
<ul id="lista">
<li id="pag1">
<label id="label1" for="input1">
Hola, soy Luis.<br/>
Bienvenido a mi web personal.<br/>
Antes de nada,<br/>
¿podrías indicarme tu nombre?<br/>
</label>
<input type='text' id="input1" autofocus autocomplete='off'/>
</li>
<li id="pag2">
<label id="label2">
<span id='nombre'>Buenos días X.</span>
Me llamo Luis Almerich de Haro. Además de trabajar como creativo en la agencia <a href='http://siroppe.com/'>Siroppe</a>, estudio Publicidad y Relaciones Públicas en la universidad CEU de Valencia.</br>
Nací hace 21 años en un pequeño pueblo de la costa gaditana y, desde que era un niño, me ha fascinado el mundo de la publicidad. También tengo otras pasiones como la tecnología, música, lectura, deporte y arte.</br>
Me defino como una persona muy curiosa. Me encanta aprender cosas nuevas y, al igual que esta web, soy un lienzo en blanco en el que queda mucho por completar.</br>
¿Te interesaría saber algo más sobre mí?</br>
</label>
</li>
<li id="pag3">
<label id="label3">Voy a hablar un poco sobre mis cualidades. Tengo una actitud positiva hacia cualquier trabajo y gran facilidad para comunicarme y relacionarme con mis compañeros. Confianza en el trabajo, adaptabilidad dentro del entorno laboral y en el trabajo en equipo, auto-motivación y pasión en el entorno laboral.</br>También he participado en diversos voluntariados:<ul><li>Organización del festival de publicidad la Lluna 2014, a cargo de CSG Servicios.</li><li>Organización del cóctel de navidad del Colegio Publicitario 2014.</li><li>Miembro activo del Observatorio Beyond The Line desde Septiembre del 2014.</li><li>Colaborador de la marca Maru Cruz.</li></ul></br>Di mi gran paso al mundo laboral trabajando para <a href='http://www.estudihac.com/'>Estudi{H}ac</a> como New Business and Research.</p><p>Soy proactivo, me gusta participar en concursos, eventos y actividades. Durante el curso 2014/2015 participé en el concurso anual de publicidad Naranja Below, donde obtuve el segundo puesto. También participé en NASA Space Apps Challenge 2015, donde obtuve una mención especial por la mejor presentación y manera de vender un proyecto.</label>
</li>
</ul>
Right now I'm not using pag3 because of this problem. Also, I know about the ASCII problems, I will fix them as soon as I can :)
As you can see, nothing special. What am I doing wrong? I just want to show the content of pag2 even when the user is returning from other web.
The $(window).on('hashchange' event is not actually firing when you come back from another site. The hash it's just there, since the beginning.
You will need to check for the hash in document.ready:
$( document ).ready(function() {
if(window.location.hash) {
// Fragment exists, do your staff to use it
}
);

Bootstrap dropdown and Jquery click function

I'm trying to make an action when someone click on a element of my dropdown.
I don't understand why, click function doesn't work.
My html code :
<div class="row">
<div class="dropdown col-lg-12">
<button class="btn btn-success dropdown-toggle" type="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="true">
Veuillez sélectionner la manière dont vous souhaitez nous contacter
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li>Etre rappelé</li>
<li>Envoyer un message</li>
</ul>
</div>
</div>
My Jquery code :
var phoneForm = $("#phoneForm");
console.log($("#callback"));
console.log($("#phoneForm").hasClass("hidden"));
$("#callback").click(function(){
console.log("entre dans la fonction click");
if(phoneForm.hasClass("hidden")){
console.log("entre dans le if");
phoneForm.removeClass("hidden");
}
});
Never it goes in click function.
Thanks
It looks like your javascript code is getting executed before those elements exist,
I suggest you to try like this
$(function(){ // Wait until you have all html printed
var phoneForm = $("#phoneForm");
console.log($("#callback"));
console.log($("#phoneForm").hasClass("hidden"));
$("#callback").click(function(){
console.log("entre dans la fonction click");
if(phoneForm.hasClass("hidden")){
console.log("entre dans le if");
phoneForm.removeClass("hidden");
}
});
});
Use JQuery version above 1.9.1
with following code
$(function(){ // Wait until you have all html printed
var phoneForm = $("#phoneForm");
console.log($("#callback"));
console.log($("#phoneForm").hasClass("hidden"));
$("#callback").click(function(){
console.log("entre dans la fonction click");
if(phoneForm.hasClass("hidden")){
console.log("entre dans le if");
phoneForm.removeClass("hidden");
}
});
});

Categories

Resources