I have a load more button on my page
<a class="btn btn-link border-top px-3 mt-5" role="button" id="reveal">Load more</a></p>
And an onclick function that loads content inside this div:
<div id="ajax-content" class="row m-0">
</div>
The script works and loads more content every time I click the button:
<script>
$('#reveal').on('click', function() {
$('#ajax-content').load('/wp-content/themes/template/ajax-news.php?offset=4');
$('#ajax-content').attr('id', '#ajax-contented');
})
</script>
But I need the offset-variable to increase by 4 every time I click it, so the content that loads is not the same. Hope anyone can point me to the right direction to make this work.
To achieve this you could use a data attribute on the a element which you increment by 4 on each successive click event:
$('#reveal').on('click', function(e) {
e.preventDefault();
let offset = ($(this).data('offset') || 0) + 4;
//$('#ajax-content').load('/wp-content/themes/heidner/ajax-aktuelt.php?offset=' + offset);
$('#ajax-content').html(offset);
$(this).data('offset', offset);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Last flere saker</p>
<div id="ajax-content" class="row m-0"></div>
This would also be possible with a global variable, but they are bad practice and should be avoided where possible.
In addition, note that changing id attributes at runtime is also not good practice. In this case it would stop the repeated clicks from updating the content. As such I removed that line.
Related
I have two buttons, both without links, and want to add a link to one when the other is clicked. How can I make one button with an onclick give a link attribute to something else on the page? If not a button, maybe a div?
The following is my current code:
<div class="container">
<div class="jumbotron" style="background-color:#000000 !important;">
<img id="myImage" src="images/closed.png" style="width:100%">
<p id="texthere"></p>
<div class="container">
<div class="row">
<div class="col">
<button onclick="document.getElementById('myImage').src='images/open.png'" class="btn btn-primary active btn-block">Open Eyes</button>
</div>
<div class="col">
<button onclick="document.getElementById('myImage').src='images/closed.png'"class="btn btn-primary active btn-block">Close eyes</button>
</div>
</div>
</div>
Thank you in advance for your help.
*Edited to clarify and pose as a question.
I think you may be confused about how HTML links work. HTML has the a tag for elements that a user can click to go to a different URL. The (worse) alternative is to use an onclick handler to redirect the user by setting the value of window.location.
To make a button that creates a link on the page, put a script tag at the bottom of the body that attaches a listener to a button that, when called, places a link on the page.
<script type="text/javascript">
var button = document.getElementById('my-button'); // This button has to exist.
button.addEventListener('click', function() {
var link = document.createElement('a');
link.href = 'google.com'; // Or wherever you want the link to point.
document.body.appendChild(link);
});
</script>
While there are many ways to do what you want, without knowing what programming skills you have and what you want to see on the screen, perhaps this sort of structure would help you. Replace your current onclick handlers on the BUTTONs:
<button id="open" class="btn btn-primary active btn-block">Open Eyes</button>
<button id="close" class="btn btn-primary active btn-block">Close eyes</button>
<script>
document.getElementById("open").addEventListener("click", function() {
changeState('open');
});
document.getElementById("close").addEventListener("click", function() {
changeState('closed')
});
function changeState(state) {
document.getElementById("myImage").src = 'images/' + state + '.png';
var new_para = document.createElement("p");
var new_link = document.createElement("a");
new_link.setAttribute("href", "https://www.google.com/search?" + state);
var new_link_text = document.createTextNode("Search for '" + state + "'");
new_link.appendChild(new_link_text);
new_para.appendChild(new_link);
document.body.appendChild(new_para);
}
</script>
I have a modal with a grid of buttons representing different html components. When one of the buttons is pressed, some html is supposed to be injected into the page once the modal closes. However, I'm having trouble targeting the specific column where the html is to be injected. Here's my code:
<div class="row" id="newRow">
<div class="col-md-12 column">
<button class="btn addElement" href="#" data-toggle="modal" data-target="#add-element"><i class="fa fa-plus fa-3x add-item"></i></button>
</div>
</div>
And in my js file I have some code to assign an id to the column div (since there could potentially be many columns with this addElement button) that looks like this:
...
$(this).parent().next().children().find('.column').assignId();
...
Up to this point, everything works well. I'm having no trouble getting the column a unique id (defined in my assignId() function).
As I mentioned, the addElement button gets clicked, opening a modal which is when this code is executed:
$(document).on('click', 'button.addElement', function (e) {
e.preventDefault();
$('#add-element').modal('show').draggable();
var col = $('button.addElement').parent();
// debugging in the browser verifies that the colId
// successfully stores the id attribute for the column
var colId = col.attr('id');
addElements(colId);
});
...
function addElements(colId) {
$('#insert-paragraph').on('click', function () {
var html_content = '<div class="box" data-type="paragraph">...</div>';
$("#newRow").find("#"+colId).html(html_content)
$('#add-element').modal('hide');
});
}
It's on this line: $("#newRow").find(colId).html(html_content); that I'm having the issue. My guess is that the formatting for find(...) is wrong and that I can't just insert a variable like that, but I've tried a few different things and nothing seems to be working.
Any help is very much appreciated.
Thanks!
UPDATE:
#juvian suggested writing a few of the variables' values to the console:
console.log(colId);
console.log($("#newRow")).length;
console.log($("#newRow").find("#"+colId).length);
console.log($("#newRow").find("#"+colId).html());
I logged these values twice. First, just before passing colId into the addElements function and in the addElements function immediately after $(#newRow").find("#"+colId).html(html_content); The results of those two tests are as follows:
Values prior to running addElements:
console.log(colId); = 8153-1076-641d-3840
console.log($("#newRow")).length; = Object[div#newRow.row.clearfix]
console.log($("#newRow").find("#"+colId).length); = 1
console.log($("#newRow").find("#"+colId).html()); = <button class="btn addElement"...>...</button>
Values after the insert-paragraph button is pressed:
console.log(colId); = 8153-1076-641d-3840
console.log($("#newRow")).length; = Object[div#newRow.row.clearfix]
console.log($("#newRow").find("#"+colId).length); = 1
console.log($("#newRow").find("#"+colId).html()); = <div class="box box-element" data-type="paragraph">...</div>
Interestingly enough, it appears like everything is working like I'd expect it to, however, when it's all said and done, the addElement button remains and the page still renders this:
<div id="newRow" class="row clearfix">
<div id="32aa-ab91-f50d-c3b3" class="col-md-12 column ui-sortable">
<button class="btn addElement" data-target="#add-element" data-toggle="modal" href="#">
<i class="fa fa-plus fa-3x add-item"></i>
</button>
</div>
</div>
.find as most jquery functions, takes a css selector as parametre. Unfortunately, colId is just a string, so it matches no elements (unless colId is html, span or something like that)
You are just missing adding the id selector at the beginning to do an id match:
.find("#"+colId)
I guess The parent of button is a div here which has no id.
var col = $('button.addElement').parent();
thus var colId is getting no value.give that div an id and it should be fine.
So I've made a function that, when you click on a button, a certain div comes up with its own content. When clicking on the button again, the div will hide and another div will show up. This div will always show up when none of the other three divs aren't selected.
The problem is when I'm adding an href tag with an anchor link which is connected to each div, that I must click twice on the button before the hidden div will show.
Check fiddle here: http://jsfiddle.net/449r8Lwv/
So as you can see, when you click on one of the buttons, nothing happens except that the url changes which is a good thing. But clicking AGAIN on the same button lets you show the hidden div. This is not what I want, I want the div show up the first time you click on the button already.
Also, when going directly to the url with an anchor name in it, It will immediately show the div with it's content that is connected to the anchor, that's a good thing. But then if you click another button again, it will show the div that must normally show when NONE of the divs aren't selected which is not the case.
Example: You go to url website.com/test.html#2. Then when you click on button 3, then content of the connected div must come("3") up but instead the div(named #text) will come up when that one should only come up if none of the divs that are connected to the buttons arent showing up.
HTML:
1
2
3
<br><br><br>
<div id="clicks">
<a class="click" id="showInfo" data-target=".1"><button>1</button></a>
<a class="click" id="showDataInput" data-target=".2"><button>2</button></a>
<a class="click" id="showHistory" data-target=".3"><button>3</button></a>
</div>
<div class="1 target" style="display: none;"><a name="1">1</a></div>
<div class="2 target" style="display: none;"><a name="1">2</a></div>
<div class="3 target" style="display: none;"><a name="1">3</a></div>
<div id="text">"I WANT THIS DIV GONE EVERYTIME I LET DIV 1, 2 OR 3 SHOW BY CLICKING THE BUTTONS. BUT SHOW UP AGAIN WHEN 1, 2 OR 3 IS NOT SHOWING/SELECTED"</div>
JavaScript/jQuery
<script>
$(document).ready(function () {
var $targets = $('.target');
$('#clicks .click').click(function () {
var $target = $($(this).data('target')).toggle();
$targets.not($target).hide();
$('#text').css('display', $('div.target:visible').length ? 'none':'')
/*$('#contact_info').toggle(!$targets.is(':visible'));*/
});
});
</script>
<script>
function doToggle(num) {
var target = $('div.target' + num);
target.toggle();
$('.target').not(target).hide();
$('#text').css('display', $('div.target:visible').length ? 'none' : '')
}
$('#clicks .click').click(function () {
var num = $(this).data('target');
doToggle(num);
});
function handleHash() {
doToggle("." + location.hash.substring(1));
}
window.onhashchange = handleHash;
$(handleHash);
</script>
Thank you a lot.
ps: in the fiddle I only put the second script part because of some issues when I put the other part aswell. If you test it local you should use the whole JavaScript/jQuery part.
Since the URL is changing, you need to put doToggle(..) in the main section of your code.
Another problem is the data-target. jQuery may evaluate the number as a number. So .1 will become 0.1. We can add the . in JS.
<div id="clicks">
<button>1</button>
<button>2</button>
<button>3</button>
</div>
<div class="1 target" style="display: none;"><a name="1">1</a></div>
<div class="2 target" style="display: none;"><a name="1">2</a></div>
<div class="3 target" style="display: none;"><a name="1">3</a></div>
<div id="text">"I WANT THIS DIV GONE EVERYTIME I LET DIV 1, 2 OR 3 SHOW BY CLICKING THE BUTTONS. BUT SHOW UP AGAIN WHEN 1, 2 OR 3 IS NOT SHOWING/SELECTED"</div>
and the JavaScript:
function doToggle(num) {
var target = $('div.target' + num);
target.toggle();
$('.target').not(target).hide();
$('#text').css('display', $('div.target:visible').length ? 'none' : '')
}
$('#clicks .click').click(function () {
var num = '.' + $(this).data('target');
if (num === '.' + location.hash.substring(1)) {
doToggle(num);
}
});
function handleHash() {
doToggle("." + location.hash.substring(1));
}
if (location.hash.substring(1).length > 0) {
doToggle('.' + location.hash.substring(1));
}
window.onhashchange = handleHash;
$(handleHash);
Edited:
In you script before, doToggle was working, but after it executed, the url would change, making it look like doToggle wasn't working. The click handler should only perform the toggle if the hash url is the same as the toggled div.
http://jsfiddle.net/449r8Lwv/12/
I'd suggest to remove dots in your data-target attribute.
So, your HTML will look like this:
1
2
3
<br><br><br>
<div id="clicks">
<a class="click" id="showInfo" data-target="1"><button>1</button></a>
<a class="click" id="showDataInput" data-target="2"><button>2</button></a>
<a class="click" id="showHistory" data-target="3"><button>3</button></a>
</div>
<div class="1 target" style="display: none;"><a name="1">1</a></div>
<div class="2 target" style="display: none;"><a name="1">2</a></div>
<div class="3 target" style="display: none;"><a name="1">3</a></div>
<div id="text">"I WANT THIS DIV GONE EVERYTIME I LET DIV 1, 2 OR 3 SHOW BY CLICKING THE BUTTONS. BUT SHOW UP AGAIN WHEN 1, 2 OR 3 IS NOT SHOWING/SELECTED"</div>
And you can try it here.
Change
$('#clicks .click')
To
$('#clicks.click')
This should solve your problem.
So remove the space in your selector
example: jsfiddle
There is flaw in your code thats why it requires two click to show the div.
Flaw: when user clicks on a link/button say "1" first time both your click and onhashchange handler is getting fired one after another. i.e clickHandler is first display the div 1 which is again gets hidden by your onhashchange handler call.
Next time when you click on same link 'No hashchange will occur' and hence only click handler is getting fired which in turn display the div correctly.
Solution: I suggest you should only use click handler because of the nature of your requirement. Or if it doesn't fit your requirement, you can set global variable to track if one of the event is fired and check its value before calling doToggle in your hashchangehandler.
I am using dynamic div content and toggling between them on clicks, works well but is there a way to retain the last viewed div when the user clicks forward and backward on his browser? Thanks.
<script>
$(".settings").click(function() {
var id = this.id;
if ($("." + $(this).attr('rel')).css('display') == 'none') {
$('.n_tab').hide();
$('.p_tab').hide();
($("." + $(this).attr('rel')).show());
}
});
</script>
<div class="settings" rel="n_tab">
<div class="title info_2_Title">
Notifications</div>
</div>
<div class="settings" rel="p_tab">
<div class="title info_2_Title">
Privacy</div>
</div>
<div id="MasterContainer">
<div class="n_tab" style="display: none;"> the N DIV </div>
<div class="p_tab" style="display: none;"> the P DIV </div>
</div>
Try using a library like history.js to set that up. Internally it will use the pushState API, or fall back to url fragments if the browser doesn't support that.
You could try adding an id to each tab and appending that in an object or array each time a div is selected.
Define an array history = []; outside the click event and in your click event something like
history.push($(this).id);
If you wanted to keep more detailed data you could use a json object and append to it.
Thanks for the help guys, but after fiddling ard with History.js, I still couldn't get it to work, in the end I used a cookie to store the state and then check it when the page with dynamic div loads.
$(function() {
var x = $.cookie('tab_cookie');
($(x).show());
if (x == '.m_tab') {
var btn = document.getElementById('<%= btnLoadm.ClientID %>');
if (btn) btn.click();
}
});
I have a li,some other elements like divs, inputs inside this li,and everything inside the gridview.
I have a onmouseover="calcRoute();" on li.
PROBLEM : I have noticed that on hovering on inside element divs and coming out of element divs to the parent div causes the calcRoute(); to execute again ,ie bind google maps again, which causes a flickering due to map rebind.
TRIED : onmouseenter and onmouseleave,but it wont support in all browsers
<li onmouseover="calcRoute(8.4572136,76.94017529999996);return false; ">
<div class="li-inner">
<input type="image" name="ctl00$ContentPlaceHolder1$FESearchListingControl1$dlPhotoView$ctl01$imgPhotoView" id="ctl00_ContentPlaceHolder1_FESearchListingControl1_dlPhotoView_ctl01_imgPhotoView" src="../UploadedImages/House2469-22-8-2012.jpg" style="height:142px;width:219px;border-width:0px;">
<div class="title">
<a id="ctl00_ContentPlaceHolder1_FESearchListingControl1_dlPhotoView_ctl01_lblPropName" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$FESearchListingControl1$dlPhotoView$ctl01$lblPropName','')">Halloween</a>
<div class="star"></div>
</div>
<div class="address">
<div class="left-location">
<span id="ctl00_ContentPlaceHolder1_FESearchListingControl1_dlPhotoView_ctl01_lblDistrict">Trivandrum</span>
</div>
<div class="right-price"><span class="WebRupee">Rs</span>
<span id="ctl00_ContentPlaceHolder1_FESearchListingControl1_dlPhotoView_ctl01_lblPrice">500.00</span>
</div>
</div>
</div>
</li>
You can attach an id to the li elements and pass this id to the calcRoute function.
onmouseover="calcRoute(8.4572136,76.94017529999996, this.id);
Then, in this function you can set a flag for this li element that it's been hovered before.
var hoveredItems = {}; // this is a global object
function calcRoute(x,y,id) {
// put this control on top so that recurring operations will be prevented from being run.
if(hoveredItems[id]) return;
else hoveredItems[id] = true;
..
}
Maybe this helps...