<a href preventDefault works every second time - javascript

I have a trash icon which user clicks on to delete current element from database. I want to make it work with ajax if user has javascript enabled. There are multiple items on page.
Don't know why but even after adding preventDefault, href works like regular href instead of performing ajax. It triggers ajax request without refreshing window only every second time I click on trash icon.
Do you know where is the problem?
$('.delete_bulletin').on('click', function (e) {
console.log('event');
e.preventDefault();
$.get($(this).attr('href')).done(
function () {
reloadBoardContent();
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bulletin_board">
<div class="bulletin_card">
<i>4. apríl 2018 14:50</i>
<h4>NAME</h4>
<p></p><p>htrhr</p><p></p>
<a class="delete_bulletin" href="/bulletin-board/delete/35/"><img style="max-height: 20px" src="/static/bulletin_board/icons/trash.png"></a>
</div>
<hr>
<div class="bulletin_card">
<i>4. apríl 2018 14:49</i>
<h4>NAME</h4>
<p></p><p>fdsafdfs</p><p></p>
<a class="delete_bulletin" href="/bulletin-board/delete/34/"><img style="max-height: 20px" src="/static/bulletin_board/icons/trash.png"></a>
</div>
<hr>
</div>

I'm pretty sure (but needs confirmation) that your reloadBoardContent() is updating the div where this <a> is located.
If that's the case, the anchor will be replaced and the event won't trigger to the newly created ones.
The solution is to use delegate events, which will make it work for dynamically added elements.
Do this instead:
$('#bulletin_board').on('click', '.delete_bulletin', function (e) {
If you don't replace the <div id="bulletin_board" itself but only its contents, everything shall be fine from now on.

Related

How to make both href and jquery click event work

I have a reporting function answerCardInnerLinkReportingCall which gets invoked on click on <a> tag inside a specific div. I use event.preventDefault(); to override the default click behavior.
Currently I am redirecting the user to the target url in the reporting function after sending all the reporting parameters using window.open('http://stackoverflow.com/', '_blank'); method.
jQuery(document).on('click','#answerCard a', function(event) {
event.preventDefault();
answerCardInnerLinkReportingCall(this);
});
If I use onclick function in the tag I would have returned true and it would make href work without me redirecting the user manually but is it possible to do the same in click handler? I can't use onclick since I dont have control over the html data.
I wanted to check if there is a better way of implementing this?
Edit1: Adding sample HTML
<div class="answer" style="display: block;">
<div class="well">
<div id="answerCard" answercardid="check_phone_acard">
<h3 id="answerTitle">check your phone</h3>
<div><ol class="answerSteps"><li>Go to <a title="Link opens in a new window" href="https://test.com" target="_blank">Check phone</a>. If prompted, log in.</li></ol></div>
<label id="seeMoreAnswer">Displaying 1 of 1 steps. </label></div>
<!-- Utility Section -->
<div class="util">
<span class="pull-left"><a id="viewFull" href="/test.jsp?sid=52345">View full article ?</a></span>
<span class="pull-right">
</div>
</div>
</div>
</div>
I guess you dont need to use any 'event.preventDefault();' if you want to use links native functionality after the script executed.
try like this
jQuery(document).on('click','#answerCard a', function(event) {
//event.preventDefault();
alert('script running');
answerCardInnerLinkReportingCall(this);
});
also created JS Fiddle. check it out.
You can use javascript's:
window.location.href = 'http://url.here.com';
To tell the browser to navigate to a page. Hope it helps.
Other way can be of returning true or false from answerCardInnerLinkReportingCall and depending on that call or dont call event.PreventDefault();
Try something like this:
$('#answerCard a').click(function(event) {
var loc = $(this).attr('href');
event.preventDefault();
answerCardInnerLinkReportingCall(loc, this);
});
function answerCardInnerLinkReportingCall(loc, that){
// your code to do stuff here
window.open(loc, '_blank');
}
See this demo fiddle

How to change a word in a h2 when certain page is clicked on

I'm trying to change a certain word in the title of a page dynamically with javascript depending on which link in the nav is clicked on. So for instance, if the "Asia" link is clicked I want the h2 to display: "You are in Asia" or if the "Europe link is clicked I want the h2 to say: "You are in Europe."
The html for the nav bar:
<div id="zone-nav">
<a href="" id="surge-btn"</a>
<a href="" id="latin-btn"</a>
<a href="" id="africa-btn"</a>
<a href="" id="asia-btn"</a>
</div>
The html I have thus far for the title that needs to be changed: `
<h2 id="zoneName">You are in<span id="zoneName"></span></h2>`
I know I need to write a function to determine what link is pressed, but I am a little confused on how to approach this.
if you add some extra markup to your html, you can use a single jQuery event handler:
<div id="zone-nav">
<a class="zone-select" href="" id="surge-btn">Surge?</a>
<a class="zone-select" href="" id="latin-btn">Latin</a>
<a class="zone-select" href="" id="africa-btn">Africa</a>
<a class="zone-select" href="" id="asia-btn">Asia</a>
</div>
now the event handler:
$(document).ready(function() {
$(".zone-select").on("click", function() {
$("#zoneName").html($(this).html());
};
});
Firstly you need to deal with your duplicate id here:
<h2 id="zoneName">You are in<span id="zoneName"></span></h2>
Note we cannot have the same id otherwise we don't know how to get an element by it's id. So remove the uneeded one on the h2:
<h2>You are in <span id="zoneName"></span></h2>
Then add event's to your a tags:
<div id="zone-nav">
<a onclick="update('Surge')" id="surge-btn" >item1</a>
<a onclick="update('Latin')" id="latin-btn" >item2</a>
<a onclick="update('Africa')" id="africa-btn" >item3</a>
<a onclick="update('Asia')" id="asia-btn" >item4</a>
</div>
Note: This can be done purely in JavaScript or be done easily in jQuery. But since you did not mention it I will not be using jQuery. We could iterate through by ClassName and have the links be a class, but that's no more simple then the way above.
For the JavaScript we need to return false to prevent the default behavior of a anchor tag:
function update(text) {
document.getElementById("zoneName").innerHTML = text;
return false;
}
Here is a working Fiddle
Would there be a way to keep the updated text in the even if the page reloads?
Yes there is a way to do this without having to use a server-sided language. What I will do is use HTML 5 web storage, note this will only work for browsers that support HTML 5 (which is all of the modern ones), you can use cookies if you need support for older browsers that work similarly for the following example. In this case I will be using sessionStorage which saves the information even until the browser is closed.
I will emulate a href to the same page for the <a> tags, we need to do this because we need to save out information before we move to a new page. After I save I will call location.reload() that will act as a refresh. Note that you could make this move to an entirely new page as well, just include the script on the new page and use window.location.href = "newPageUrl" ( jsfiddle prevents me from moving to a new page ).
The HTML will be the same but the JavaScript will be updated as followed:
window.onload = function() { // When the page loads
if(sessionStorage.zoneName) { // Check if the session exist
// update the page with the session info
document.getElementById("zoneName").innerHTML = sessionStorage.zoneName;
}
}
function update(text) {
sessionStorage.zoneName = text; // store the text into a session called "zoneName"
location.reload(); // reload the page
return;
}
Here is a working Fiddle
Here's an example of what you could do for the africa-btn (this will require jQuery, I hope that's alright):
$(document).ready(function() {
$("#africa-btn").on("click", function() {
$("#zoneName").html("Africa");
};
// Other buttons here
});
What this is doing is attaching an action to the "click" event of the africa-btn anchor tag. When it's clicked it should update the span's html as described above. You can add further click events in a similar way.
Using $("#africa-btn") to bind the click event is a way to do it specifically for that one button, so you'll have to do it for each id.
This would update the selected zone in the dom
<div id="zone-nav">
<a id="africa-btn" onclick="updateZone('africa'); return false;"> </a>
<a id="asia-btn" onclick="updateZone('asia'); return false;"> </a>
</div>
function updateZone(countryName){
document.getElementById('zoneName').innerText = countryName;
return false;
}
are you looking for something like this :
Simple html and javascript only:
http://jsfiddle.net/q9L37c32/
Asia

Need jquery to activate a click through by clicking on a different div

I was hoping someone could help...I'm new to Jquery ....all I want to achieve is a click through on a hyperlinked image but this occurs when a completely separate div on another part of the page is clicked on rather than the hyperlinked image I just mentioned. .......the hyperlinked image needs to be invisible also. In case anyone is wondering why I need this ....it's because I want my own custom button rather than the standard one that comes with a CMS that I'm using and it can't be changed....it's basically a work around the owners of the system suggest.
Here's what I thought would work
<style>
#my-custom-button{
margin: 0 auto;
width: 200px
}
#the-standard-button{
display : none
}
</style>
<div id="my-custom-button">
<img src="../images/order-now.png">
</div>
<div id="the-standard-button">
<?php
proprietary PHP here that renders the standard button
?>
</div>
<script type="text/javascript">
<!--
$(function(){
$("#my-custom-button").click(function(){
$("#the-standard-button").click();
});
});
-->
</script>
The whole
<?php propiertary blah blah ?>
makes it hard to decipher but my guess is that the handler is being generated for whatever is being created by php, i.e. the php generates
<button id="phpButton">
blah
</button>
and then a handler like
$("#phpButton").click(....)
Notice that the handler is NOT on "#the-standard-button". So, you need make sure that you are using the correct selector when calling the click() in $("#my-custom-button").click(...)
Check out this jsFiddle. Notice which secondary click event is fired.
I'm not sure I understand your question perfectly, if what you want is that when You click on one button it will act as though the other was clicked.
Here is a solution that will work IF the default button is also an anchor tag (<a>)
HTML:
<div id="newButton">
<img src="/theimage.jpg"/>
</div>
<div id="oldDiv">
<img src"oldImage.png"/>
</div>
JQuery:
jQuery(document).ready(function($){
$("#oldDiv").hide();
$("#newDiv > a").click(function(){
window.location = $("#oldDiv>a").attr("href");
});
});

Modifying a page from JQM dialog

What I'd like to achieve is a page that has a couple of buttons inside a div. When the user presses one of these buttons a dialog opens, asking follow up questions. After this the user is returned to the same page but the div with the buttons is hidden.
What I've tried is the following, inside a JQM page i have div called buttons which contains the buttons(logically). this opens the dialog and also calls a function which saves to local storage which button was pressed. Then the dialog opens which actually sends the data to the server.
For some reason the div is never hidden when I return from the dialog. I even tried to save a variable to the sessionStorage and hide the div on pageload, but seems that the page load event does not fire when returning from the dialog. Any suggestions or am I missing something basic?
<div class="ui-grid-b" id="buttons">
<div class="ui-block-a"></div>
<div class="ui-block-b"></div>
<div class="ui-block-c"></div>
</div><!-- /grid-b -->
// the dialog:
<div data-role="dialog" id="Popup" data-overlay-theme="b" data-theme="a" class="ui-corner-all">
<form>
<div style="padding:10px 20px;">
<h3>Heading</h3>
<textarea name="comments" id="popuptextarea"></textarea>
<button type="submit" data-theme="b" onClick="save()">Selvä</button>
</div>
</form>
</div>
I have two javascript functions which try to save the data and also hide the div,
function savePushedButton(color) {
//save which button was pressed to local storage
$('#buttons').hide();
console.log("asd");
}
function save() {
//send data to server
}
onclick is your problem (onchange also), do not use it with jQuery Mobile. jQuery Mobile has already started transition to the dialog, before onclick has been triggered. You will need to manually bind a click event to the button and hide buttons before transition to dialog can occur.
Here's a working example: http://jsfiddle.net/Gajotres/uhsfs/
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('click', '#test-button', function(){
$('#buttons').hide();
savePushedButton($(this).attr('data-color'));
});
});
function savePushedButton(color) {
console.log(color);
$.mobile.changePage('#Popup', {transition: 'pop', role: 'dialog'});
}

toggle div keep as it is after page refresh or change

In this example. I need my div is open if page is change or refresh.
I have given my HTML and Javascript.
This is where my code is live http://jsfiddle.net/wasimkazi/fauNg/1/
$(".widget2").hide();
$(".box2").toggle(function() {
$(this).next(".widget2").slideDown(200);
}, function() {
$(this).next(".widget2").slideUp(200);
});
$(".inner").hide();
$(".box").toggle(function() {
$(this).next(".inner").slideDown(200);
}, function() {
$(this).next(".inner").slideUp(200);
});?
<div class="box2"><h3>Basketball</h3>
</div>
<div class="widget2" style="display: block; "><div class="widget"><div class="box"><h3>Australia</h3></div>
<div class="inner" style="display: block; ">
<ul class="leagues">
<li class="even">Australian NBL</li>
</ul>
<div class="clear-both"></div>
</div></div>
</div>?
Use javascript coockie to save the Open and close state for each menu, and read the state when page loads. this is the only way to go since every time page is refreshed, everything is reset.
When you make a change, you can change what's after the # at the end of the url. Then when the page is reloaded, you read the value after the hash in $(document).ready() and make the changes accordingly.
You can use the is function to check if your div is hidden and show it
if($(".selector").is(":hidden"))
$(".selector").show();
Furthermore as #mikel said, put it inside document ready function for checking on pageload.
$(document).ready(function(){
if($(".selector").is(":hidden"))
$(".selector").show();
});

Categories

Resources