/r/jquery
News, articles, plugins and tutorials for jQuery, the world's most popular Javascript library! Covering jQuery Core, jQuery UI, jQuery Mobile, and other related projects.
News, articles, plugins and tutorials, covering jQuery Core, jQuery UI, jQuery Mobile, and other related projects.
Resources:
Other subreddits you may like:
Does this sidebar need an addition or correction? Tell us here
/r/jquery
Anyone else using Jquery for new projects now? Jquery homepage mentions Jquery 4 coming soon with modern improvements, I wonder if Jquery can develop into a framework like React or Vue?
I wrote this for myself, figured someone else might find it useful. It overrides the .val() function to take a date or certain string values (today, tomorrow, +15d) and converts them to ISO format for the control. Only applies to input=date, all other controls are unaffected. 2.2k, or 901 bytes minimized.
I am trying to load and display a specific div, .row on the right pane on my website. This works fine, but unfortunately a lot of scripts are not loaded (Getting "failed to load script/url" in the console and as a results some buttons are not working.
I thought about loading the divs that precede the .row class, but that just seems to result in my website from reloading over and over, presumably because we are reloading content twice and either the jquery is triggering on that, or something else is going on.
The code itself just is added as a code snippet in a site wide header, to a wordpress site. I am using a 2 column layout where I use the theme provided widget on the left (jobs shown in a summary listing) and I use a raw html widget on the right with just some html for a placeholder.
So jobs are shown on the left, and the content of those jobs is shown on the right.
Is my way of loading a page into another page the right method? What could be the problem here?
The code itself:
jQuery(document).ready(function($) {
// Function to load job details into the right pane
function loadJobDetails(jobUrl) {
$.ajax({
url: jobUrl,
method: 'GET',
success: function(response) {
var tempDiv = $('<div>').html(response);
var jobDetails = tempDiv.find('.row');
// Remove classes we don't want to see
jobDetails.find('.careerfy-jobdetail-search-style5, .col-md-2, .col-md-3, .col-md-4, .careerfy-footer-nine').remove();
$('.job-details-content').html(jobDetails);
$('.job-details-content').addClass('active');
// Scroll the right pane to the top
$('.job-details-content').scrollTop(0);
var scripts = [];
tempDiv.find('script').each(function() {
var script = $(this);
if (script.attr('src')) {
scripts.push({ src: script.attr('src'), type: 'external' });
} else if (script.html()) {
scripts.push({ content: script.html(), type: 'inline' });
}
});
var styles = [];
tempDiv.find('link[rel="stylesheet"]').each(function() {
styles.push($(this).attr('href'));
});
styles.forEach(function(href) {
if (!$('link[href="' + href + '"]').length) {
$('<link>', { rel: 'stylesheet', type: 'text/css', href: href }).appendTo('head');
}
});
function loadScriptsSequentially(scripts, index) {
if (index >= scripts.length) return;
var script = scripts[index];
if (script.type === 'external') {
$.getScript(script.src).done(function() {
loadScriptsSequentially(scripts, index + 1);
}).fail(function() {
console.error('Failed to load script:', script.src);
loadScriptsSequentially(scripts, index + 1);
});
} else {
try {
$.globalEval(script.content);
} catch (e) {
console.error('Failed to execute inline script:', e);
}
loadScriptsSequentially(scripts, index + 1);
}
}
loadScriptsSequentially(scripts, 0);
},
error: function() {
$('.job-details-content').html('<p>Error loading job details. Please try again.</p>');
}
});
}
function bindJobDetailsEvents() {
$('.jobsearch-pst-title a').off('mouseenter mouseleave click');
$('.jobsearch-pst-title a').on('mouseenter', function() {
var jobUrl = $(this).attr('href');
loadJobDetails(jobUrl);
});
$('.jobsearch-pst-title a').on('click', function(e) {
e.preventDefault();
var jobUrl = $(this).attr('href');
loadJobDetails(jobUrl);
});
}
function jobsearch_job_pagenation_ajax(page_type, page_number, total_jobs, load_all, extra_params) {
$.ajax({
type: "GET",
url: "", // Replace with the actual URL
data: { type: page_type, page: page_number, total: total_jobs, load_all: load_all, params: extra_params },
success: function(response) {
$('#job-listing-container').html(response.jobs);
bindJobDetailsEvents();
var firstJob = $('.jobsearch-pst-title a').first();
if (firstJob.length) {
var firstJobUrl = firstJob.attr('href');
loadJobDetails(firstJobUrl);
} else {
$('.job-details-content').html('');
}
},
error: function(xhr, status, error) {
console.error("Error fetching job listings:", error);
}
});
}
if ($('body').hasClass('jobsearch-joblisting-classic-wrap') || window.location.pathname.includes('/jobs-listing')) {
var firstJob = $('.jobsearch-pst-title a').first();
if (firstJob.length) {
var firstJobUrl = firstJob.attr('href');
loadJobDetails(firstJobUrl);
}
bindJobDetailsEvents();
}
$(document).on('click', '.jobsearch-page-numbers a', function(e) {
e.preventDefault();
var pageNumber = $(this).text();
jobsearch_job_pagenation_ajax('job_page', pageNumber, '2387', 'true', '');
});
$(document).on('click', '.prev-pli-con a, .next-pli-con a', function(e) {
e.preventDefault();
var currentPage = parseInt($('.jobsearch-page-numbers .current').text());
var pageNumber = $(this).hasClass('prev') ? currentPage - 1 : currentPage + 1;
jobsearch_job_pagenation_ajax('job_page', pageNumber, '2387', 'true', '');
});
});
I have a web page that I want to use to display a table showing all the reports that are scheduled on a specific date or range of dates, I want the user to be able to select the date or range of dates in a date picker and if no date or range of dates is selected, I want the table to show only the reports scheduled for today. I have a function that runs a SQL query to return the relevant reports and I want to pass in the date or range of dates that are selected in the date picker or just return reports for today if no date or range of dates has been picked by the user. I have a controller that takes the data frame containing the list of reports and renders it as a table. I also have the HTML template.
I have created the majority of it but I am struggling to get it to work correctly, when i run it I am getting an error List argument must consist only of tuples or dictionaries.
I have tried using chatgpt to help but going round in circles.
Below is the function containing the SQL query: def get_list_of_scheduled_reports(start_date=None, end_date=None): base_sql = """ SELECT id, project, filename, schedule, time_region, day_of_week_month, 'Apps' AS source_table FROM bi_apps_schedule WHERE status = 'active' """
# Set start_date to today if not provided
if start_date is None:
start_date = datetime.now().strftime('%Y-%m-%d')
# SQL conditions for date filtering
date_conditions = """
AND (
(schedule = 'daily' AND day_of_week_month = EXTRACT(DOW FROM %s::timestamp))
OR (schedule = 'weekly' AND day_of_week_month = EXTRACT(DOW FROM %s::timestamp))
OR (schedule = 'biweekly_even' AND MOD(EXTRACT(WEEK FROM %s::timestamp), 2) = 0 AND day_of_week_month = EXTRACT(DOW FROM %s::timestamp))
OR (schedule = 'biweekly_odd' AND MOD(EXTRACT(WEEK FROM %s::timestamp), 2) = 1 AND day_of_week_month = EXTRACT(DOW FROM %s::timestamp))
OR (schedule = 'monthly' AND day_of_week_month = EXTRACT(DAY FROM %s::timestamp))
OR (schedule = 'quarterly' AND day_of_week_month = EXTRACT(DAY FROM %s::timestamp))
)
"""
# Append date filter for range, if end_date is provided
if end_date:
date_conditions += " AND %s <= schedule_date AND schedule_date <= %s"
# Extend base SQL with date filtering
base_sql += date_conditions
parameters = [start_date] * 8 # Repeat start_date for each EXTRACT function
if end_date:
parameters.extend([start_date, end_date])
# Add UNION with Tableau reports (repeat the same logic)
base_sql += """
UNION ALL
SELECT
id,
project,
workbooks AS filename,
schedule,
time_region,
day_of_week_month,
'Tableau' AS source_table
FROM
bi_tableau_apps_schedule
WHERE
status = 'active'
""" + date_conditions
parameters.extend(parameters) # Duplicate parameters for UNION part
base_sql += " ORDER BY time_region ASC, source_table ASC;"
# Execute query with parameters
df = pd.read_sql_query(base_sql, get_jerry_engine(), params=parameters)
return df.to_dict(orient="records")
Below is the controller: @main_bp.route('/scheduled_reports_wc') @login_required def scheduled_reports(): start_date = request.args.get('start_date') end_date = request.args.get('end_date')
# Fetch scheduled reports from the database in list of dictionaries format
data = db_queries.get_list_of_scheduled_reports(start_date, end_date)
# Always return JSON data directly if requested by AJAX
if request.is_xhr or request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify(data) # Ensures JSON response with list of dictionaries
# Initial page load; render template
today_date = datetime.now().strftime('%Y-%m-%d')
return render_template('insights_menu/scheduled_reports_wc.html',
data=json.dumps(data), # Pass initial data for page load as JSON string
today=today_date)
Below is the HTML template: {% extends "layout.html" %}
{% block body %}
<div class="row"> <h4 id="table_header">Scheduled BI Reports</h4> </div> <div class="row"> <div class="col-sm"> <input type="date" id="startDatePicker" placeholder="Start date" class="form-control" value="{{ today }}"/> </div> <div class="col-sm"> <input type="date" id="endDatePicker" placeholder="End date" class="form-control"/> </div> </div> <div class="row"> <div class="col-sm" id="table_row"> <table class="table table-striped table-bordered dt-responsive hover" cellspacing="0" id="data_table" role="grid"> <thead> <tr> <th>ID</th> <th>Project</th> <th>Filename</th> <th>Schedule</th> <th>Time Region</th> <th>Day of Week / Month</th> <th>Source Table</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> {% endblock %}{% block scripts %}
<script> $(document).ready(function() { // Check initialData structure before loading into DataTables let initialData = {{ data | safe }}; console.log("Initial data structure:", initialData); // Should be list of dictionaries // Initialize DataTables with list of dictionaries let table = $('#data_table').DataTable({ lengthMenu: [10, 25, 50], pageLength: 25, data: initialData, // Expecting list of dictionaries here responsive: true, bAutoWidth: false, dom: '<"top"f><"clear">Brtip', buttons: ['copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5'], columns: [ { title: "ID", data: "id" }, { title: "Project", data: "project" }, { title: "Filename", data: "filename" }, { title: "Schedule", data: "schedule" }, { title: "Time Region", data: "time_region" }, { title: "Day of Week / Month", data: "day_of_week_month" }, { title: "Source Table", data: "source_table" } ] }); }); // AJAX call on date change $('#startDatePicker, #endDatePicker').on('change', function() { let startDate = $('#startDatePicker').val(); let endDate = $('#endDatePicker').val(); if (startDate) { $.ajax({ url: '/scheduled_reports_wc', data: { start_date: startDate, end_date: endDate }, success: function(response) { console.log("AJAX response:", response); // Check structure here table.clear().rows.add(response).draw(); // Add data to table }, error: function(xhr, status, error) { console.error("Failed to fetch reports:", status, error); } }); } }); });I need to do a special search in an html table using jquery and ai is not helping
When i make a image slider with jquery this "thing" is in the corner of the first image. How do i remove it?
Thing to note is that i impliment the first image with a css class and not <img src="">. Rest of the images is with an array.
Edit 1: The url was just a misspell by me in this example code. The path to the pic is correct and i can even see the picture. So how is it that the picture is broken/doesn't exist, when the path is correct, i can see the picture(with the display that its not working) and without jquery its just fine?
.examplecClass {
background-image: url(images/picture.jpg);
}
I'm new to jquery and ajax development. I've been troubleshooting and trying to wrap my head around some already written code that makes use of ajaxStart and ajaxStop. It's still using the now deprecated syntax as the jquery version is slightly older. The code doesn't appear to behave how I would expect it to and I've been tearing my hair out trying to figure it out. I'm not sure if I'm misunderstanding. Basically, on the first load of the web page using the javascript code, the ajaxStart does not execute, but the ajaxStop code does when a function is called that is making an ajax request. If that same function is called later on an event other than the initial page load (e.g. someone clicks a button), the ajaxStart code executes before the function ajax request and then the ajaxStop code executes after. I've only found one or two similar areas where someone reported similar behavior, but it wasn't clear if it's a bug or user error.
I can't really share the code for work reasons, but in a nutshell it's something like the following:
$(document).ready(function() {
var parm1 = null;
$(document).ajaxStart(() => {
//doing some start stuff
});
$(document).ajaxStop(() => {
//doing some stop stuff
});
customFunction(parm1);
function customFunction(parm1) {
$.ajax({
method: "GET",
url: https//www.somerandomurl.com/apiendpoint
success: function(parm2) {
//doing some stuff with response
} else {
//do some other stuff when unsuccessful
}
},
error: function() {
//doing some stuff on errors
}
});
});
When that customFunction is called on the first load of the web page only the code within the ajaxStop block is executed after the function finishes.
Is this how ajaxStart works? Is there a workaround or way I could force the ajaxStart block to execute on page load other than maybe posting the code within ajaxStart completely outside of the ajaxStart block? Or maybe that's the workaround.
I'm trying to implement a change to my code, however I can't seem to get it to connect. Basically, I keep getting an Internal 500 error with an ajax call to one of my files, but I'm not understanding how that's possible when I've used the same structure to call to other files in the same system.
My ajax structure:
$.ajax{( type:'POST', url: 'https://testerdomainname/bin/submitA.php', asyn: false, data:{varname:varname}, success: function(data){ console.log(data); } });
This structure has worked with all my other files, even with calling to a much simpler form of the file (/bin/submitB.php) used for another case, however for some reason with submitA.php it always gives me the 500 error (and yes, the call needs to be in https). I have been losing my mind with this for the past week, if I could get some possible insight as to why it's giving me this error and if it's simply a false positive, I would greatly appreciate it.
I'm new to programming.
I'm trying to create an API that will download images from Pinterest by the link.
ERROR:
There is no error and also no output. I don't know whether my input link is not being received in the backend or it was not able to call the route (/uploadlink/).
Here is my code.
File 1: main.py
app = FastAPI()
templates = Jinja2Templates(directory='templates')
app.mount("/static", StaticFiles(directory='static'), name='static')
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get('/', response_class=HTMLResponse)
async def get_basic_form(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.post('/uploadlink/')
async def get_basic_form(link: str = Form(...)):
if not os.path.exists('image_folder'):
os.makedirs('image_folder')
url = link
HEADERS = ({'User-Agent':''})
os.chdir('image_folder')
webpage = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(webpage.content, "html.parser")
images = soup.find_all("img", class_='hCL kVc L4E MIw')
images_list = []
real_image = ""
for img in images:
if img.has_attr('src'):
images_list.append(img['src'])
for i in range(len(images_list)):
if images_list[i].__contains__('736x'):
real_image = images_list[i]
r = requests.get(f"{real_image}")
with open('image.png', 'wb') as f:
f.write(r.content)
return {"image"}
File 2: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pinterest</title>
</head>
<body>
<h1>Pinterest Image downloader</h1>
<form id="upload-form" enctype="multipart/form-data"></form>
<input type="text" name="link" id="link" required><br>
<button type="submit" value="submit" id="downloadBtn">Download</button>
</form>
<div id="result">
<h2>Pinterest Image:</h2>
<img id="generated-image" src="" alt="Generated Image" style="display: none; max-width: 100%; height: auto;">
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$('upload-form').on('submit', function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url: '/uploadlink/',
type: 'POST',
data: formData,
processData: false,
contentType: 'application/json',
success: function(imageResponse){
$('#generated-image').attr('src', '/image_folder/image.jpeg');
$('#generated-image').show();
},
error: function(xhr, status, error){
$('#generated-image').text('Error: ' + xhr.responseText);
}
});
});
});
</script>
</body>
</html>
If a page has old references to jquery libraries apparently that puts PCI compliance at risk because old jquery libraries contain vulnerabilities.
Is there a the long-term, future proof way to link to a jquery library so that it is always going to be up to date and not get picked up by scans for vulnerabilities?
As much of an ELI5 approach would be really wonderful.
My primary objective is to be able to click on a column in any of multiple rows and copy the contents of that cell to the clipboard.
In the example given in the codepen linked below, I will build a row incorporating contact information for each person in the database, including unique info like a record number. I would like the user to be able to simply click on the email address to copy it to the clipboard.
Would much prefer not to use a button; I'm trying to let the user just click on the cell, though enclosing the string in a SPAN could work. If a button is necessary, so be it.
The jQuery code attached seems to work well, but only for one instance on the page. Evidently I need to pass the string to be copied into the jQuery function - not sure how.
A secondary objective, perhaps the topic of future research, will be to have the cell contents visually indicate that the content has been copied (i.e. by transitioning to red and bold, than back to previous setting.)
Would be very grateful for any assistance. I suspect that this is a relatively straight-forward adaptation of the code, but it's been a very long time since I've worked with JS and jQuery, and my abilities were somewhat sparse even then.
I have dates (7 days each way from current date) in a selectbox, there are also Previous and Next buttons for it.
eg. <-- [SELECTBOX] -->
However, when clicking, say, the Next button (and vice-versa), it works as expected (the date changes in the select box), however when I click Previous, the select does not change, but it does triggered.
Heres the code:
$( '#select-fixturedate' ).on('change', function(e){
get selectbox selected value and do ajax call
});
$('#calendar_navigation-previous').on('click', function(e) {
$('#select-fixturedate option:selected').attr('selected', 'false');
$('#select-fixturedate option:selected').next().attr('selected', 'selected');
$('#select-fixturedate').trigger('change');
});
$('#calendar_navigation-next').on('click', function(e) {
$('#select-fixturedate option:selected').attr('selected', 'false');
$('#select-fixturedate option:selected').prev().attr('selected', 'selected');
$('#select-fixturedate').trigger('change');
});
TIA
I need help with the steps, "research strategy", "concept and validation", etc.
I want to make it responsive just like the original website however I can't seem to recreate it.
I have a plugin that is being assigned to each control individually, but when I click one, all of them respond. What do I need to change?
The code is here:
https://jsfiddle.net/mapsedge/45bntgpo/15/
p.s. It doesn't function cosmetically the way it should - the entries come up hidden for some reason - but the problem is both controls going at the same time, not the visibility of the items. I assure you it works fine on my app.
I have a table which gets data from backend and is populated in frontend using a loop and then make a datatable for it , but i have issue that in datatable search box the row can be searched with id too which is for development purpose only and we want it should not be used to search , i made a column for id at index 0 and give its visible to false. I paste this code in datatable code
"columnDefs": [
{
"targets": [0],
"visible": false,
"searchable": false
}
]
While visibility false is working fine still the searchable is not working , how can i stop row to be searched by that id.
I heard that SVG support was greatly increased and SVG elements append was fixed in jQuery 3 or something (https://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element). But what exactly lines of code they mended or added, that now treat <svg> tags somewhat more special? Because I didn't find very much of "svg" keywords in actual jQuery source code.
So I have the following form. The form is cloneable, so there may be several on the page. When the "Save" button is clicked, I can get the form, and the value of the form ID attribute. But how do I get the form fields and their values? I am hing a heck of a time with the proper syntax. So how would I get the .val of the field "Model"?
<form class="SignificantDiv" name="VechicleForm" id="VechicleForm2" method="post">
<input type="hidden" name="IDNum" value="3">
<input type="hidden" name="MbrTbl" value="MemberInfo">
<input type="hidden" name="MbrNum" value="1">
<fieldset class="FormTbl" id="EditProfileFormTbl">
<ul>
<li class="col25" title="Vechicle year">
<label for="Year" id="YearLbl" class="bregLbl">Year</label>
<input class="bnotes" type="text" id="Year" name="Year" value="1963" />
</li>
<li class="col25" title="Vechicle Make">
<label for="Make" id="MakeLbl" class="bregLbl">Make</label>
<input class="bnotes" type="text" id="Make" name="Make" value="Dodge" />
</li>
<li class="col25" title="Vechicle Model">
<label for="Model" id="ModelLbl" class="bregLbl">Model</label>
<input class="bnotes" type="text" id="Model" name="Model" value="Dart" />
</li>
<li class="col25" title="Vechicle Trim Level">
<label for="Trim" id="TrimLbl" class="bregLbl">Trim</label>
<input class="bnotes" type="text" id="Trim" name="Trim" value="GT" />
</li>
<li class="col100" title="More Info">
<label for="Comments" id="CommentsLbl" class="bregLbl">Comments</label>
<textarea id="ExtraInfo" name="ExtraInfo" class="bnotes" rows="1"></textarea>
</li>
<li class="col50" title="vehicle model">
<input class="delete" type="button" id="DeleteButton" name="DeleteButton" title="Delete this vehicle" value="Delete" />
</li>
<li class="col50" title="vehicle model">
<input class="send" type="button" id="SaveButton" name="SaveButton" title="Save this vehicle" value="Save" />
</li>
</ul>
</fieldset>
</form>
Here is my JQuery:
$(".send").on("click", function(e){
e.preventDefault();
alert("Save Button Clicked");
var TheForm = $(this).closest("form")[0];
//This doesn't work
//var Model = $(this).closest("form")[0].find('input[name="Model"]').val();
//This doesn't work
//var Model = TheForm.find('input[name="Model"]').val();
//This doesn't work
//var Model = TheForm.Model.val();
//This doesn't work
//var Model = $(TheForm).("#SendTo").val();
//This one returns that there is an object, but the val() is undefined
// $(TheForm).children("Model").val();
//This one returns that there is an object, but the val() is undefined
//var Model = $(this).closest("form").children("Model").val();
alert("I need some help with the correct syntax!");
});
New to jQuery, and pretty much the title... I have a requirement to load the following html tag-based javascript and cannot figure out how to pass the params the js needs:
<script src="https://cdn.cookielaw.org/scripttemplates/otSDKStub.js" type="text/javascript" charset="UTF-8" data-domain-script="000-000-000-0000" ></script>
I can get the script loaded via $.getScript() but that data-domain-script param needs to be in there as well. Suggestions?
Hi,
We are using openid SSO authentication.
This is working fine, but there are occasions when the token will expire. This can happen when a page has been idle for a while or httpd is restarted.
This results in ajax requests receiving a 401.
I'm using ajax in the following two ways.
$.ajax(URL, {
xhrFields: {
onprogress: function(e) {
}
}
})
.done(function(res) {
})
.fail(function(res) {
console.log(res)
});
$.ajax({
type: "POST", cache: false,
data: data,
url: URL,
success: function(data) {
console.log(data)
}
});
Could someone point me in the right direction on how to handle this correctly.
Thanks
Unsure if it's ok to ask this here, if the mods dont allow me to ask this please tell me why my post wasn't allowed thank you Ive tried the suggestions ive seen online and it's either they dont work or Im doing it wrong. I understand to go to the developer tools of msedge and then go to console but everytime I input a command it comes out as invalid. I basically want to fill in a portion of a form in a website with kanji but every time I do it says special characters arent allowed. Here are some sites I tried to get solutions from:
https://devcodef1.com/news/1248163/input-field-validation-with-special-characters
How can you pass the ID of an element that is clicked on to manipulate another corresponding element, without having to write a jquery function for every single one?
So.... Let's say that I have a list of something on a page. I show a headline then have a link that says "more" after each headline to hide/show the details of the headline. So it looks something like this...
<div id="SomeBlock">
<a id="MoreDetailsLink1">More...</a>
<div id="MoreDetailsDiv1" style="display:none;">The rest of story goes here</div>
</div>
I know I could write:
$(document).ready(function(){
$("#MoreDetailsLink1").click(function(){
$("#MoreDetailsDiv1").toggle();
});
});
But, let's say that I have 25 or 100 of those headline/details elements. I really do not want to rewite a jquery function for every single one. I should be able to do something to pass or grab the "More..." link id to toggle the correct more details div.
How do I do that? If I click on MoreDetailsLink47, I need MoreDetailsDiv47 to toggle.
Hi there,
So I'm trying to set up a weird slider for a client who is very insistent on it being a certain way. Basically I have 8 full height sections (.howwedoit-slidewrapper) with a fixed image background. Then in each of those "slides" I have a text wrapper (.howwedoit-textwrapper) and inside is the text (.howwedoit-statictext). The text should always be in the middle of the screen but only visible when its parent slide is behind it. If the screen is perfectly split between two slides then the top half of one text should show and the bottom half of the next and everything in-between. I've gotten the code really close my only problem is when the slides are centered or near centered instead of the text only partly showing, no text at all shows. My attempts to fix this make it where the text ends up overlapping with the next slide.
This is in WordPress which is why there are no $.
jQuery:
jQuery(document).ready(function(){
jQuery(window).on('scroll', function(){
var windowHeight = jQuery(window).height();
var scrollTop = jQuery(window).scrollTop();
jQuery('.howwedoit-slidewrapper').each(function(){
var slideTop = jQuery(this).offset().top;
var slideBottom = slideTop + jQuery(this).outerHeight();
var textWrapper = jQuery(this).find('.howwedoit-textwrapper');
var textHeight = textWrapper.outerHeight();
var slideHeight = jQuery(this).outerHeight();
var slideVisibleTop = Math.max(slideTop, scrollTop);
var slideVisibleBottom = Math.min(slideBottom, scrollTop + windowHeight);
var newTop = (slideHeight - textHeight) / 2;
// Check if the text is fully visible within its parent slide
if (slideVisibleTop <= (slideTop + newTop) && slideVisibleBottom >= (slideTop + newTop + textHeight)) {
textWrapper.addClass('visible');
textWrapper.css('translateY', newTop + 'px'); // Move this line inside the condition
} else {
textWrapper.removeClass('visible');
}
});
}).scroll(); // Trigger scroll event on page load
});
CSS:
.howwedoit-textwrapper {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
opacity: 0; /* Initially hide text */
}
.howwedoit-statictext {
position: relative;
}
.visible {
opacity: 1 !important; /* Ensure the opacity is overridden */
}
.howwedoit-statictext > div, .howwedoit-statictext > div > h2 {
position: relative !important;
}
I have a resizable element with a label inside with a fieldname. I'd like to set a minWidth and minHeight value based on the size of the label. Below doesn't work. What am I missing? Here's also a link to a fiddle:
https://jsfiddle.net/mapsedge/5qtrya2x/73/
<div class='elementResizable'>
<label>
[10] buyer-first-name
</label>
<div class="ui-resizable-handle ui-resizable-nw" id="nwgrip"></div>
<div class="ui-resizable-handle ui-resizable-ne" id="negrip"></div>
<div class="ui-resizable-handle ui-resizable-sw" id="swgrip"></div>
<div class="ui-resizable-handle ui-resizable-se" id="segrip"></div>
<div class="ui-resizable-handle ui-resizable-n" id="ngrip"></div>
<div class="ui-resizable-handle ui-resizable-s" id="sgrip"></div>
<div class="ui-resizable-handle ui-resizable-e" id="egrip"></div>
<div class="ui-resizable-handle ui-resizable-w" id="wgrip"></div>
</div>
$('.elementResizable').resizable({
handles: {
'nw': '#nwgrip',
'ne': '#negrip',
'sw': '#swgrip',
'se': '#segrip',
'n': '#ngrip',
'e': '#egrip',
's': '#sgrip',
'w': '#wgrip'
}
});
$( ".elementResizable" ).resizable( "option", "minWidth", function(){
const $this = $(this);
const label = $this.find("label");
return label.width();
});
$( ".elementResizable" ).resizable( "option", "minHeight", function(){
const $this = $(this);
const label = $this.find("label");
return label.height();
});
Hi. My data provider starts to send me data in 2 different structures
(differences in imageValue field: object in about group and array in banner group)
{
"valuesToUpload": [
{
"groupId": "about_2",
"groupTitle": "",
"fields": [
{
"fieldType": "image",
"valueId": "cd262467-e683-4b1a-8fff-b22c42722f2c",
"toUpload": true,
"imageValue": {
"imageId": 27606887612,
"imageSchema": "profile_composition",
"url": "http://img10/image/1/1.YaE0cFYle0oRLlTPlS7HAwtEINoMkYFRuB_k"
}
},
{
"fieldType": "image",
"fieldName": "example_images",
"valueId": "5b394732-28c1-424c-a5c8-5edd553a3711",
"toUpload": true,
"imageValue": {
"imageId": 27606306642,
"imageSchema": "profile_composition",
"url": "http://img40/image/1/1.j_RTsLassXjnkzZKMn-0czdeML_SxCdo-c"
}
},
{
"fieldType": "image",
"fieldName": "example_images",
"valueId": "efaeca0d-9dbe-4b1c-93a1-51cb54b9ec1b",
"toUpload": true,
"imageValue": {
"imageId": 27606343705,
"imageSchema": "profile_composition",
"url": "http://img00/image/1/1.xNLAhbas-l50pn65eZTqgqHrazl2.r39lMZMqeTovl4Cj2EY"
}
},
{
"groupId": "banner",
"groupTitle": "banner",
"fields": [
{
"fieldType": "image",
"imageValue": [
{
"imageId": 0000001,
"toUpload": true,
"valueId": "efaeca0d-9dbe-4b1c-93a1-51cb54b9ec00",
"imageSchema": "profile_composition",
"url": "https://20.img.st/image/1/link1"
},
{
"imageId": 0000002,
"toUpload": false,
"valueId": "efaeca0d-9dbe-4b1c-93a1-51cb54b9ec01",
"imageSchema": "profile_composition",
"url": "https://20.img.st/image/1/link2"
}
],
"fieldName": "banner",
"fieldTitle": "banner"
}
]
}]
}
],
"reload": {
"on": false
}
}
I found out how to select only separate object format (about_2):
{"valuesToUpload":[
.payload.valuesToUpload[]|{groupId,groupTitle,fields:[.fields[]| select(.valueId != null)]}
]}
and get only "about_2" section.
But how to write jquery to recompile banner section to same forma and not lost about_2 section. banner section must be like :
{
"groupId": "banner",
"groupTitle": "banner",
"fields": [
{
"fieldType": "image",
"valueId": "efaeca0d-9dbe-4b1c-93a1-51cb54b9ec00",
"toUpload": true,
"imageValue": {
"imageId": 0000001,
"imageSchema": "profile_composition",
"url": "https://20.img.st/image/1/link1"
}
},
{
"fieldType": "image",
"valueId": "efaeca0d-9dbe-4b1c-93a1-51cb54b9ec01",
"toUpload": true,
"imageValue": {
"imageId": 0000002,
"imageSchema": "profile_composition",
"url": "https://20.img.st/image/1/link2"
}
}
]
}
I am looking for a jquery plugin for timepicker. that lets you use a array to disable few Times. I am working on a booking system so i want to disable a certain times of a certain date etc. Any help will be appreciated.